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 |
|---|---|---|---|---|
3,777,503 | 3,777,626 | is it possible to change what the user types without pressing enter? this is a console program in C | Is this possible? The idea is typing a password and it being translated to asterisks on the fly- pretty much like a password field on HTML. I've written this code, but it converts the input AFTER the user presses enter, not while he/she is typing.
#include <stdio.h>
#include <string.h>
#include <iostream>
int main()
... | If you do want to get some extra points from the teacher, you could look into the function int getch() which does what you want. It is located in the header file conio.h.
Googling for getch should provide you with some info - MSDN and cplusplus.com are my favorite pages.
|
3,777,525 | 3,777,627 | Returning a unique_ptr from a class method C++0x | If my class SomeType has a method that returns a element from the map (using the key) say
std::unique_ptr<OtherType> get_othertype(std::string name)
{
return otMap.find(name);
}
that would enure the caller would recieve a pointer to the one in the map rather than a copy? Is it ok to do this, or would it try and ca... | The model of unique_ptr is transfer of ownership. If you return a unique_ptr to an object from a function, then no other unique_ptr in the system can possibly refer to the same object.
Is that what you want? I highly doubt it. Of course, you could simply return a raw pointer:
OtherType* get_othertype(const std::string&... |
3,777,609 | 3,777,699 | Questions regarding Vector Array of Structs | I made a post about this yesterday, but it is a fairly different question. Not sure if I should make a new question or just reply to the old one but here goes.
Basically I am setting up my vector array of structs as follows..
class Debugger : public Ogre::SimpleRenderable
{
struct DebugVertex
{
Ogre::Ve... | What's the exact compiler error? My guess is that DebugVertex does not conform to the interface required for inclusion in STL containers like std::vector, possibly because Ogre::Vector3 needs work.
Can you include the declaration for Ogre::Vector3?
|
3,777,643 | 3,777,655 | How can I get a compilation error on accidental construction? | Given 2 classes:
...
class Grades{
public:
Grades(int numExams) : _numExams(numExams){
_grdArr = new double[numExams];
}
double GetAverage() const;
...
private: // The only data members of the class
int _numExams;
double *_grdArr;
};
class Student{
public:
Student(Grades g) :... | This is because Grades has a single argument constructor which acts as a converting constructor. Such a constructor takes an int argument and creates an object of type Grades.
Therefore the compilation is successful.
Make the consructor of 'Grades' explicit
explicit Grades(int numExams);
This will disallow
Grades g = ... |
3,777,824 | 3,777,854 | Project with both c and c++ files | Can I have a project that has some parts written in c and other parts written in c++ ?
Is this possible ?
| Yes.
If you have control of the C code, then inside your C header files you should have:
#ifdef __cplusplus
extern "C" {
#endif
// normal header stuff here
#ifdef __cplusplus
};
#endif
That way they can be properly interpreted when included by both C and CPP code files.
If you include C code in your C++ via a header... |
3,777,857 | 3,777,873 | Whether variable name in any programming language takes memory space | e.g.
int a=3;//-----------------------(1)
and
int a_long_variable_name_used_instead_of_small_one=3;//-------------(2)
out of (1) and (2) which will acquire more memory space or equal space would be aquire?
| Both occupy the same amount of memory. Variable names are just to help you, the programmer, remember what the variable is for, and to help the compiler associate different uses of the same variable. With the exception of debugging symbols, they make no appearance in the compiled code.
|
3,778,111 | 3,778,141 | What loop to use for an iteration that might be interrupted before the end? | I have a range of memory to parse. If I find a certain sequence of bytes before the end, I interrupt the iteration. I wonder which loop I should prefer here:
while(i < end && !sequenceFound ) {
// parse
i++;
}
Or
for( i; i < end && !sequenceFound; i++ ) {
// parse
}
This is used in a method of a class tha... | Why not just use break; at the point that the need to "interrupt" the loop is encountered. This seems like the language feature that most idiomatically expresses your intent. It usually means that you can do without the extra boolean state tracking variable.
If you need to know whether the iteration terminated early yo... |
3,778,268 | 3,778,429 | "carbon-copy" a c++ istream? | For my very own little parser framework, I am trying to define (something like) the following function:
template <class T>
// with operator>>( std::istream&, T& )
void tryParse( std::istream& is, T& tgt )
{
is >> tgt /* , *BUT* store every character that is consumed by this operation
in some string. If afterwar... | Unfortunately, streams have only very minimal and rudimentary putback support.
The last times I needed this, I wrote my own reader classes which wrapped a stream, but had a buffer to put things back into, and read from the stream only when that buffer is empty. These had ways to get a state from, and you could commit ... |
3,778,450 | 3,778,459 | Is local static variable per instance or per class? | I want to know if I have a static variable within a class member function if that variable will only have an instance for that class or for each object of that class. Here's an example of what I want to do.
class CTest
{
public:
testFunc();
};
CTest::testFunc()
{
static list<string> listStatic;
}
Is listStatic ... | It is per that function CTest::testFunc() - each invokation of that member function will use the same variable.
|
3,778,602 | 3,778,665 | Boost FOR_EACH Over A Ptr_Vector? | I'm currently having fun trying to learn some of the Boost libary. I'm currently doing what I guess will be a future homework project (semester hasn't started yet). However, this question is not about the homework problem, but about Boost.
Code:
/* AuctionApplication.h */
class AuctionApplication : boost::noncopyable
{... | ptr_vector takes ownership of heap allocated objects and presents each object as a reference so you don't need dereferencing and you use . instead of -> to access member variables/functions. e.g.
Bid highestBid = 0;
BOOST_FOREACH (Bid& bid, bids_)
if (bid.GetAuction()->GetName() == auction->GetName())
highe... |
3,778,704 | 3,778,775 | std::pair expecting a 'type', but I am giving it a type | This is my code:
typedef std::hash_multimap<Vertice<VerticeType, WeightType>*, Edge<VerticeType, WeightType>*> ght;
std::pair<ght::iterator, ght::iterator> getEdgesFromVertice(Vertice<VerticeType, WeightType>*);
When I try to compile it, it gives me an error saying:
error: type/value mismatch at argument 1 in template... | This looks like it is in a template and VerticeType etc. are template parameters. In that case you are missing typename:
std::pair<typename ght::iterator, typename ght::iterator> ...
Dependent names are assumed to not name types unless typename is used.
|
3,778,799 | 7,285,235 | How do I start a CUDA app in Visual Studio 2010? | Direct Question: How do I create a simple hello world CUDA project within visual studio 2010?
Background: I've written CUDA kernels. I'm intimately familiar with the .vcproj files from Visual Studio 2005 -- tweaked several by hand. In VS 2005, if I want to build a CUDA kernel, I add a custom build rule and then exp... | CUDA TOOLKIT 4.0 and later
The build customisations file (installed into the Program Files\MSBuild\Microsoft.Cpp\v4.0\BuildCustomizations directory) "teaches" Visual Studio how to compile and link any .cu files in your project into your application. If you chose to skip installing the customisations, or if you installe... |
3,778,818 | 3,778,914 | How to delete a template? | I'm having trouble with deleting my template.
My template and destructor:
template<class S, class T>
class Consortium
{
private :
map<const S, Node<T>*> m_consortiumMap;
Heap<T>m_consortiumHeap;
public :
~Consortium();
void Insert(const S key, T toAdd);
void Update(const S key);
void Rem... | This is wrong on its face:
delete &m_consortiumHeap;
You must only delete things that you allocated with new. m_consortiumHeap is part of the class and gets automatically allocated when the class gets allocated and automatically deallocated when the class gets deallocated. You cannot and must not explicitly delete it.... |
3,778,867 | 3,778,907 | Error with catching std::runtime_error as std::exception | we have a funny problem with try catch and std::runtime_error.
Can someone explain to me why this is returning "Unknown error" as output ?
Thanks very much for helping me !
#include "stdafx.h"
#include <iostream>
#include <stdexcept>
int magicCode()
{
throw std::runtime_error("FunnyError");
}
int funnyCatch()
{
... | The problem is with this line. Because throw with an expression uses the static type of that expression to determine the exception thrown, this slices the exception object constructing a new std::exception object copying only the base object part of the std::runtime_error that e is a reference to.
throw e;
To re-throw... |
3,778,928 | 3,779,067 | Count number of chars in char array including spaces until null char | I'm trying to count the number of chars in a char array including the space until the end of the string.
The following compiles but doesn't return the correct value, I'm trying to use pointer arithmetic to interate through my array.
int numberOfCharsInArray(char* array) {
int numberOfChars = 0;
while ... | Perhaps I'm missing something, but why not just:
int numberOfCharsInArray(char* array) {
return strlen(array);
}
...or even:
int numberOfCharsInArray(char* array) {
return std::string(array).length();
}
|
3,779,017 | 3,779,270 | How to get the vertices of a polygon described by planes | This is a repost of a question that went unanswered
basically I am trying to model a map that has the following format:
Each brush defines a solid region. Brushes define this region as the intersection of four or more planes. Each plane is defined by three noncolinear points. These points must go in a clockwise orienta... | I don't think there is any other option: the only information you have about the vertices is contained in the planes, and the only way to get the vertices from the planes is to determine their intersections, so you will have to loop through the possibilities.
To start:
If you are sure the planes do indeed bound a volu... |
3,779,138 | 3,779,194 | how to free memory from a set | I got a set that includes pointers to an allocated memory, I am using the clear method forexample : setname.clear();
and the set itself is getting cleared and his pointers but I still get memory leaks because the allocated memory stays uncleared for some reason.
| std::set's clear() method does remove elements from the set. However, in your case set contains pointers that are being removed, but the memory they point to is not released. You have to do it manually before the call to clear(), for example:
struct Deleter
{
template <typename T>
void operator () (T *ptr)
{
... |
3,779,227 | 3,779,252 | Why is this vector iterator not incrementable? | I'm trying to delete the vector's content and I'm getting an error - vector iterator is not incrementable, why is that?
This is my destructor:
City::~City()
{
vector <Base*>::iterator deleteIterator;
for (deleteIterator = m_basesVector.begin() ; deleteIterator != m_basesVector.end() ; deleteIterator++)
... | erase invalidates the iterator. You can't use it any more. Luckily for you, it returns an iterator that you can use:
vector <Base*>::iterator deleteIterator = m_basesVector.begin();
while (deleteIterator != m_basesVector.end()) {
deleteIterator = m_basesVector.erase(deleteIterator);
}
Or:
m_basesVector.clear();
A... |
3,779,278 | 3,779,344 | Problem with % n *** %n in writable segment detected *** C++ i Qt | Problem with % n * %n in writable segment detected * C++ i Qt
I have program that process big data, that can't be modified. In one file we encounter "100% na" and application stop.
When I checked it with debuger, it return * %n in writable segment detected *.
I can't change visible that data, user must see "100% na".... | Use prepare to prepare the query. Then insert the values using bindValue. Prepared statements should always be used in such scenarios, as they handle the escaping of special characters for you.
|
3,779,350 | 3,779,424 | Deprecated conversion from string const. to wchar_t* | Hello I have a pump class that requires using a member variable that is a pointer to a wchar_t array containing the port address ie: "com9".
The problem is that when I initialise this variable in the constructor my compiler flags up a depreciated conversion warning.
pump::pump(){
this->portNumber = L"com9";}
This w... | If portNumber is a wchar_t*, it should be a const wchar_t*.
String literals are immutable, so the elements are const. There exists a deprecated conversion from string literal to non-const pointer, but that's dangerous. Make the change so you're keeping type safety and not using the unsafe conversion.
The second one fai... |
3,779,466 | 3,779,941 | Is there an equivalent for __if_exists in gnu c++? | __if_exists is a microsoft specific keyword for testing existence of identifiers at compile time:
msdn:__if_exists
It can come in very handy at "faked" template specialization as in some cases it provides a really much more simple, readable and better performing way than other methods like "real" specialization or over... | That's a crappy keyword in my opinion...
Unfortunately, it doesn't exist in gcc as far as I know, but then I may simply not know about it.
The proper C++ way to handle this is through the use of Concepts, ie adapt the operations carried on the type depending on some requirements.
Usually, it's carried out with traits r... |
3,779,489 | 3,779,590 | Parallel inheritance trees, where classes from one tree have containers of classes from another | I really didn't know how to specify the problem in the title, so here's the gist of it.
I am writing graph classes Graph, Node, and Edge, and then subclassing them into VisGraph, VisNode and VisEdge to obtain a drawable graph (in C++). I then need to further subclass those into specific classes that depend on certain d... | If in doubt, throw templates at the problem until it surrenders:
template <typename N, typename E>
class Graph {
std::vector<N> nodes;
std::vector<E> edges;
};
typedef Graph<VisNode, VisEdge> VisGraph;
typedef Graph<RouteNode, RouteEdge> RouteGraph;
You lose the inheritance (RouteGraph no longer inherits from... |
3,779,557 | 3,826,424 | How to programmatically load a Java card applet ( a .cap file ) using Visual C++/PCSC | I am currentlly on a project that requires me to load a JavaCard application Applet ( a .cap ) file to a JavaCard. Our framework is based on Visual C++ and PCSC, so we need to load the same applet to a series of JavaCards. Does anyone know how this can be processed? I mean, where should I start. Thanks!
| You are correct that this is not a trivial job.
There are differences between different javacards, but generally you need to do 4 things:
initialize secure communications with the card (because many javacards are "global platform" cards they require a secure channel)
send a command saying "i wanna install an applet"
... |
3,779,763 | 3,779,933 | Fast Algorithm for computing percentiles to remove outliers | I have a program that needs to repeatedly compute the approximate percentile (order statistic) of a dataset in order to remove outliers before further processing. I'm currently doing so by sorting the array of values and picking the appropriate element; this is doable, but it's a noticable blip on the profiles despite... | The histogram solution from Henrik will work. You can also use a selection algorithm to efficiently find the k largest or smallest elements in an array of n elements in O(n). To use this for the 95th percentile set k=0.05n and find the k largest elements.
Reference:
http://en.wikipedia.org/wiki/Selection_algorithm#Sele... |
3,779,801 | 3,779,867 | How to compile c++ in xCode for your IPhone app? | I am doing my first steps in IPhone developing. I want to use some c\c++ code but I can't find any reference of how it's done (will very appriciate if you can also refer me to your source when you give an answear)
I have a file called calc.h containing a "calculator" class with simple add and mult functions, I imported... | Whatever you were doing when you were coding just in C/C++.
For example:
#include "calc.h"
....
-(void) testCode { //obj-c
float x = 3;
float y = 8.0;
float sumOfTwo = sum(x, y);
}
Assuming that you have a function named sum in your header file similar with the one used above.
|
3,779,847 | 3,779,991 | Need help with logic on how to assign the correct value to a textbox | I am passing in a value to the form that I ultimately assign to a textbox using javascript. The value is a calculation based on values from another page/form. However, the textbox is editable.
When reloading the form with the previously saved data, I don't want the value of the textbox to be overwritten with the pre... | You can accomplish this with a couple of session variables. The first session variable is the value of the TextBox. Since you have another page generating the value for you, you can't rely on the ViewState to store the value for you, it only work with PostBacks on the page.
The second session variable is a simple boole... |
3,779,878 | 3,780,352 | How can I generate UML class diagrams from C++ source files? | With doxygen I can generate nice diagrams but doxygen lacks a deeper analysis of the relationships between classes. It recognizes derivation but other relations are not understood by the tool. Which better utilities are there (commercial or not) that generate more complete UML class diagrams out of C++ source files?
Th... | For parsing C++ code, the best tool I have used is BoUML. It is not perfect, and it won't generate the diagrams for you, but it does understand the relationships. If you pull two classes into a class diagram, it will automatically draw the relationships, and it allows you to grow the diagram by selecting a particular c... |
3,779,912 | 3,779,976 | memoryleak detection | hey i am trying to detect leaks in visual studio using :
#define _CRTDBG_MAPALLOC
#include <stdlib.h>
#include <crtdbg.h>
and in the end of the main i am typing :
_CrtDumpMemoryLeaks();
when i do all of this i am getting the the memoryleaks (what inside them) but not the places that the allocates were made , can u p... | You can't out of the box. CrtDumpMemoryLeaks only tells you if there are any memory leaks, not where the memory leak is. The CRT provides no such facility.
There are a couple of ways to accomplish something like this. One way would be to use a tool like Valgrind, which instruments the entire application and runs the ap... |
3,779,921 | 3,780,377 | Visual C++ won't create the dll file and stops at the *.lib | I inherited a dll project (Visual C++ 2002) and I'm having a lot of trouble to compile it. Even though the *.def file is in the current dir, VC will only create a lib file, instead of the dll.
Anybody knows what might be going on?
| It was actually a problem with the output dir that was pointing to a network drive. The dll was created, but placed in an odd folder.
|
3,779,937 | 3,780,051 | Compiler Optimization with Parameters | Lets say you have some functions in some classes are called together like this
myclass::render(int offset_x, int offset_y)
{
otherClass.render(offset_x, offset_y)
}
This pattern will repeat for a while possibly through 10+ classes, so my question is:
Are modern C++ compilers smart enough to recognise that wherever... | I think it's more likely that the compiler will make a larger-scale optimization. You'd have to examine the actual machine code produced, but for example the following trivial attempt:
#include <iostream>
class B {
public:
void F( int x, int y ) {
std::cout << x << ", " << y << std::endl;
}
};
class ... |
3,780,075 | 3,780,158 | Interesting C++ code snippet, any explanations? |
Possible Duplicate:
Why am I able to make a function call using an invalid class pointer
class B
{
public:
int i;
B():i(0){}
void func1()
{
cout<<“func1::B\n”;
}
void func2()
{
cout<<“i = “<<i;
}
};
int main()
{
B *bp = new B;
bp->func1();
delete... | This is the same old story of NULL (or invalid) object pointers; for the standard, calling a method on a NULL object pointer results in undefined behavior, which means that, as far as the standard is concerned, it could work perfectly fine, it could blow up the computer or kill some random people.
What happens here is ... |
3,780,111 | 3,780,169 | Deploying application question (C++) | Does someone know if there is a way to pack everything-application related into one (single) exe-file?
My product is fully written in C++, has a lot of external plugins (dll) and some external data packages. It should be accessible using the network and without installation (launch in one click).
Are there some tools... | Try an .msi file, or ClickOnce deployment (assuming Windows, assuming at least VS 2005).
Edit: Based on a comment below, I don't know in general if you can do exactly what you are asking with an arbitary set of DLLs. You can include, say, Microsoft Foundation Classes statically rather than dynamically. But the distr... |
3,780,112 | 3,780,229 | What is the equivalent C# code for this Canon SDK C++ code snippet? | What is the C# equivalent of this C++ code?
private:
static EdsError EDSCALLBACK ProgressFunc (
EdsUInt32 inPercent,
EdsVoid * inContext,
EdsBool * outCancel
)
{
Command *command = (Command *)inContext;... | This is a rough translation for illustration purposes:
private static void ProgressFunc(uint percent, object context, out bool cancel)
{
Command command = (Command)context;
CameraEvent e = new CameraEvent("ProgressReport", percent);
command.GetCameraModel().NotifyObservers(e);
cancel = false;
}
(EdsErr... |
3,780,255 | 3,780,342 | cin.get() not working | I wrote this simple program today, but I found that cin.get() refuses to work unless there are 2 of them. Any ideas?
#include <iostream>
using namespace std;
int main(){
int base;
while ((base < 2) || (base > 36)){
cout << "Base (2-36):" << endl;
cin >> base;
}
string base_st... | You are not initializing the 'base' variable, but while that will cause bugs it isn't (directly) related to the behavior you're seeing with cin, even though it will sometimes, depending on the compiler, cause you to skip loops. You're probably building in debug mode that zero-initializes or something.
That said, assumi... |
3,780,327 | 3,780,359 | C++ Template Basics - Function Accept Sub Class or Super | Say you have a sub class B which inherits from super class A. You want a function that can accept either A or B.
template <typename T>
void someFunc(T* pObj, bool someOtherArg)
{
pObj->AnInheritMethod();
if (pObj->IsASub())
{
pObj->ANonInhertMethod();
}
}
When I compile this (Visual Studio 6) I... | You don't need a function template for this; the following will do just fine:
void someFunc(A* pObj)
{
pObj->AnInheritMethod();
if (B* pObjAsB = dynamic_cast<B*>(pObj))
{
pObjAsB->ANonInheritMethod();
}
}
Or, if you prefer to use your IsASub() member function instead of dynamic_cast:
void someF... |
3,780,398 | 3,780,571 | Integrating a script language into a C++ application | I'm really new to C++ and I've come across a problem I've not been able to solve by reading documentations.
I want to embed a script language into my c++ application. That language could be javascript, lua or preferably python.
I'm not looking for something like Boost.Python / swig, something that is able to wrap my c+... | Why not use Boost.Python? You can expose your data classes to Python and execute a script/function as described here.
|
3,780,481 | 3,780,541 | What does (a+b) >>1 mean? | What does int c = (a+b) >>1 mean in C++?
| Note, that there can't be any meaningful explanation of what your code means until you explain what a and b are.
Even if a and b are of built-in type, beware of the incorrect answers unconditionally claiming that built-in right shift is equivalent to division by 2. The equivalence only holds for non-negative values. T... |
3,780,555 | 3,780,611 | c2955 error on my Double Link List project | Okay, I'm making a project that implements a Double Linked List using classes, templates and structures.
I constantly get the error:
doublelinklist.h(21) : error C2955: 'Node' : use of class template requires template argument list
when declaring the head and tail of a node in the LinkedList class.
DoubleLinkList.h:
... | Error C2955 (link) relates to the absence of a type argument list to types that require one. In your code you reference the type Node which is actually a template and requires a type argument list. The fixes are below:
First of all, in DoubleLinkedList.h in the declaration of LinkedList (in the private: section at the ... |
3,780,624 | 3,780,663 | Obfuscated way of accessing a character in string | I found today interesting piece of code:
auto ch = (double(), (float(), int()))["\t\a\r\n\0"]["abcdefghij"];
which works same as:
char str[] = "abcdefghij";
char ch = str['\t'];
Why is it even possible? Especially why is the compiler picking first char from string and using it as subscript instead of throwing error?
| I'll explain as rewrite:
auto ch = (double(), (float(), int()))["\t\a\r\n\0"]["abcdefghij"];
is equivalent to (just evaluate all the double, float, int temporaries with comma operator)
auto ch = (0["\t\a\r\n\0"])["abcdefghij"];
Now the standard says that:
x[y] == *(x + y)
No matter which one is a pointer. so you get... |
3,780,770 | 3,781,165 | Keeping modules independent, while still using each other | A big part of my C++ application uses classes to describe the data model, e.g. something like ClassType (which actually emulates reflection in plain C++).
I want to add a new module to my application and it needs to make use of these ClassType's, but I prefer not to introduce dependencies from my new module on ClassTyp... | I'll steer away from thinkng about your reflection, and just look at the dependency ideas.
Decouple what it's reasonable to decouple. Coupling implies that if one thing changes so must another. So your NewCode is using ClassType, if some aspects of it change then yuou surely must change NewCode - it can't be completel... |
3,780,898 | 3,780,928 | How are iostream objects cin, cout, cerr, and clog implemented? | iostream objects cin, cout, cerr, and clog are objects declared in the iostream header.
I'm aware that it's possible in some compilers to attempt to use these iostream objects before they are constructed, so under some circumstances they must be subject to the "static initialisation order fiasco". In those compilers w... | There's no compiler magic.
IIRC, the standard implementation is to define a global constant object in the header. In each translation unit this header is included, one such object is created. Its constructor increments a counter, its destructor decrements it. When incrementing from 0 to 1, the the console stream objec... |
3,780,994 | 3,781,164 | String reversal in C++ | I am trying to reverse the order of words in a sentence by maintaining the spaces as below.
[this is my test string] ==> [string test my is this]
I did in a step by step manner as,
[this is my test string] - input string
[gnirts tset ym si siht] - reverse the whole string - in-place
[string test my is t... | Your approach is fine. But alternatively you can also do:
Keep scanning the input for words and
spaces
If you find a word push it onto stack
S
If you find space(s) enqueue the
number of spaces into a queue Q
After this is done there will be N words on the stack and N-1 numbers in the queue.
While stack not empty do
... |
3,781,049 | 3,781,191 | Using the "This" Pointer in c++ | I've been reading about the "this" pointer on various sites (e.g. the MSDN manuals) and understand its basic uses -- returning a copy your own object or using a pointer of it for returns/comparison.
But I came across this statement:
// Return an object that defines its own operator[] that will access the data.
// T... | The this keyword basically is a pointer reference to the object that it's currently in use. In C++, this is a pointer, so to dereference it, use *this.
So, this code,
return VectorDeque2D_Inner_Set<T>(*this, index);
returns a new VectorDeque2D_Inner_Set by passing a dereferenced of itself (since the constructor wants... |
3,781,063 | 3,781,535 | How to find assignments with no effect? | In the process of automatically renaming many variables in a big project I may have created a lot of things like these:
class Foo {
int Par;
void Bar(int Par) {
Par = Par; // Nonsense
}
};
Now I need to identify those locations to correct them. E.g. into "this->Par = Par;".
Unfortunately the ... | A couple of compilers can generate warnings on this:
GCC and Clang can warn on code like this if you add the -Wshadow option. (Specifically, while they don't warn about the meaningless assignment, they do warn about the local variable Par shadowing the member variable Par - you may or may not like this.)
Embarcadero ... |
3,781,073 | 3,781,122 | Upload a file to a web server using C++ | I want to upload files from a client location to a server. At present, I have a client-server socket program by which I could send/receive files across, but I would like to improvise it.
My idea would be to transfer the file using HTTP PUT/POST from client (most of the coding on client side) to the server. Since I hav... | As stated it's not possible. C++ alone has no sockets API. (Edit: with the addition of a BSD sockets API, it's now possible).
Your implementation might provide an OS-specific sockets API, in which case your question boils down to, "how do I write an HTTP client?". To which the answer is (a) don't, or (b) read the HTTP ... |
3,781,098 | 3,781,103 | C++ textbox contents | How do I get the contents of a textbox in C++?
| Use the Win32 API GetWindowText passing in the text box's window handle.
If you want to get the text from another process use WM_GETTEXT instead with SendMessage.
|
3,781,135 | 3,781,176 | Same C++ code results in infinite loop on Windows and expected behavior on OSX | This is one of the weirder things I've seen. I'm teaching an intro C++ course at a university, and one of my students contacted me saying that his code was running forever without stopping. I briefly glanced over his code during class, and didn't see anything immediately obvious, so I had him email me his code.
Withou... | None of the input operations are checked. There are various lines like
cin >> deposit;
If the extraction from stdin fails (i.e., if the next thing in the stream is not a valid double in this case) then the fail state will be set on the stream and none of the subsequent input operations from stdin will succeed until t... |
3,781,222 | 3,781,997 | add_definitions vs. configure_file | I need to conditionally compile several parts of code, depending on whether there are some libraries present on the system or not. Their presence is determined during the CMake configuration phase and I plan to tell the compiler the results using preprocessor definitions (like #ifdef(LIB_DEFINED) ... #endif).
I know a... | Depending on the amount of libraries you use, the call of the compiler becomes large if following the second approach. So I would say for smaller projects with only 2-3 of those optional libraries follow approach 2 but if it's more like 10 or so, better follow approach 1 so that the compilation output stays readable.
|
3,781,520 | 3,782,064 | How to test if preprocessor symbol is #define'd but has no value? | Using C++ preprocessor directives, is it possible to test if a preprocessor symbol has been defined but has no value? Something like that:
#define MYVARIABLE
#if !defined(MYVARIABLE) || #MYVARIABLE == ""
... blablabla ...
#endif
EDIT: The reason why I am doing it is because the project I'm working on is supposed to ta... | Soma macro magic:
#define DO_EXPAND(VAL) VAL ## 1
#define EXPAND(VAL) DO_EXPAND(VAL)
#if !defined(MYVARIABLE) || (EXPAND(MYVARIABLE) == 1)
Only here if MYVARIABLE is not defined
OR MYVARIABLE is the empty string
#endif
Note if you define MYVARIABLE on the command line the default value is 1:
g++ -DMYVARIABLE <... |
3,781,623 | 3,781,709 | Problem with references to pointers | Why this can't compile:
// RefToPointers.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using std::cout;
class T
{
public:
T(int* value):data_(value)
{
}
int* data_;
int* getData_()
{
return data_;
}
int getValue()//<---... | getData() returns an rvalue. You can't take a reference to an rvalue pointer.
You have two choices:
1) Pass fnc() lvalues:
int* lhs = one.getData_();
int* rhs = two.getData_();
fnc(lhs, rhs);
2) Or, since you are passing pointer references, which really are the same size as pointers themselves, why not just pass poin... |
3,781,653 | 3,781,717 | Is it legal to declare a friendship with a forward declared class? | I have successfully constructed something similar to the following code in visual studio 2008:
class OpDevconfigSession;
class DevconfigSession
{
...
private
friend class OpDevconfigSession;
};
Again, this works quite well with visual studio. However, if I try to compile the code under g++ version 4.3.2, I get an... | Your code snippet is missing a colon after private. After fixing that, it Works For Me™ in g++ (http://codepad.org/XJuyEq9z).
It's also standard - you don't even need the separate forward declaration. See this example from 11.4 of the standard:
class X {
enum { a=100 };
friend class Y;
};
class Y {
int v[X... |
3,781,707 | 3,781,759 | how to pass a value of table to a variable of c++ using select in mysql++ | How to select a value from a table and store in a variable in my sql++
e.g select name from employee;
write this query in c++ and then store the name in variable e_name
I googled and I know the mysql++ tutorials tell this code but I was connecting differently... can you see what is the problem with this.
mysql_init(&m... | See the mysql++ tutorial:
http://tangentsoft.net/mysql++/doc/html/userman/tutorial.html#simple
The relevant code:
mysqlpp::Query query = conn.query("select item from stock");
if (mysqlpp::StoreQueryResult res = query.store()) {
cout << "We have:" << endl;
for (size_t i = 0; i < res.num_rows(); ++i) {
co... |
3,781,730 | 3,781,810 | C++ Header files, constructor logic, simple get/set methods | What's the thoughts on allowing simple constructor/method definitions in header files in C++. Some classes I am creating are simple data objects that compose another object say, so they need there own constructor and get/set methods. However these are usually < 3-4 lines each with the constructors using init lists. Is... | I'd vote for only putting declarations in your header file. This will make the header file more clean (no implementation cluttering your view). The user can look upon the header file to view the interface, without being confronted with irrelevant implementation details.
Putting definitions (as opposed to declarations) ... |
3,781,880 | 3,782,822 | Problem using mysql++ library | I've read the tutorial at, and I generally get how that works:
http://tangentsoft.net/mysql++/doc/html/userman/tutorial.html#simple
I am trying to build this mysql++ code, and I'm getting an error:
std::ostringstream query3;
query3<<"select pipe_id from pipe where version_id='"<<id<<"'";
std::storeQueryResult ares=quer... | The problem is that you have to use a mysql++ query object to execute a query, not an ostringstream. The ostringstream just lets you build the query string, but won't let you perform the query.
There is a tutorial that shows basic usage at:
http://tangentsoft.net/mysql++/doc/html/userman/tutorial.html#simple
To get fr... |
3,781,991 | 3,782,210 | I was trying to select rows using mysql++ | Here is my code
int main(int argc,char *argv[])
{
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,.............,"3306",0);
if (connection == NULL)
{
cout << mysql_error(&mysql);
return 1;
}
else
{
int id=1;
mysqlpp::Query query=connection.query("select * from pipe");
//query3<<"select p... | You are mixing calls to the C API and the C++ API, this approach won't work.
I suggest you look at the MySQL++ turorial, and e.g. the example at http://tangentsoft.net/mysql++/doc/html/userman/tutorial.html
In particular, replace this:
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,.............,"3306",0)... |
3,782,174 | 3,785,595 | How to use boost::error_info correctly? | I'm trying to following the examples on this page:
http://www.boost.org/doc/libs/1_40_0/libs/exception/doc/motivation.html
The minute I try the following line:
throw file_read_error() << errno_code(errno);
I get an error:
error C2440: '<function-style-cast>' : cannot convert from 'int' to 'errno_code'
How do I get th... | Sam Miller gave me a clue as to what the problem was. I just needed to include:
#include <boost/exception/all.hpp>
Thanks for your answers.
|
3,782,303 | 3,782,413 | Pointer alignment in libjpeg | From jmorecfg.h:
#define PACK_TWO_PIXELS(l,r) ((r<<16) | l)
#define PACK_NEED_ALIGNMENT(ptr) (((int)(ptr))&3)
#define WRITE_TWO_PIXELS(addr, pixels) do { \
((INT16*)(addr))[0] = (pixels); \
((INT16*)(addr))[1] = (pixels)>>16; \
} while(0)
#define WRITE_TWO_ALIGNED_PIXELS(addr, pixe... | WRITE_TWO_PIXELS and WRITE_TWO_ALIGNED_PIXELS are equivalent for little endian machines but not for big endian architecture.
[Example edited: thanks to Steve Jessop]
Let, pixels = 0x0A0B0C0D
For big endian machines, WRITE_TWO_PIXELS work as follows:
---------------------
| 0B | 0A | 0D | 0C |
---------------------
3 ... |
3,782,628 | 3,782,643 | Why does C++ not support Variable-length arrays? |
Possible Duplicate:
Variable length arrays in C++?
I am just curious, is there any particular reason why C++ does not allow variable length arrays?
| Two reasons:
C++ is based on C89 (the C standard as published in 1989). VLAs were only introduced in C99.
C++ has std::vector<> and a whole bunch of other containers, which is why I believe that C++ will never bother with VLAs. It already had them when VLAs were invented for C.
|
3,782,651 | 3,782,870 | MFC CToolBar Help/Link? | I can't find a simple CToolBar example of all things..
I created a toolbar in the resource editor, and loaded the toolbar in my code like this:
toolbar = new CToolBar;
toolbar->CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_ALIGN_TOP, CRect(0, 0, 0, 0), AFX_IDW_TOOLBAR);
toolbar->LoadToolBar(IDR_TOOLBAR);
I... | The buttons in a toolbar are disabled in MFC by default. For each button, which should be associated with a command ID, you need to have an ON_UPDATE_COMMAND_UI macro in your message map. The handler function you use in this macro will be called whenever the app is idle. This function can call the member functions of t... |
3,783,016 | 3,783,039 | Fundamental typedef operand syntax | Given:
typedef type-declaration synonym;
I can see how:
typedef long unsigned int size_t;
declares size_t as a synonym for long unsigned int, however I (know it does but) can't see exactly how:
typedef int (*F)(size_t, size_t);
declares F as a synonym for pointer to function (size_t, size_t) returning int
typedef's ... | Type declarations using typedef are the same as corresponding variable declarations, just with typedef prepended. So,
int x; // declares a variable named 'x' of type 'int'
typedef int x; // declares a type named 'x' that is 'int'
It's exactly the same with function pointer types:
int(*F)(size_t); // d... |
3,783,237 | 3,783,592 | Using a manifest causes window to remain partially blank | I am in the process of trying to make an app that has most of its development done in Visual C++ 6.0 adhere to Windows theming, or to be precise the visual styles aspect of it. The application in question is a MFC application with the MBCS characterset. Getting theming to kick in in the first place required the InitCom... | As far as I know, version 6 of the Common Controls only officially supports Unicode.
According to a blog entry by Raymond Chen, those controls work with the ANSI character set to a degree, but only for backwards compatibility reasons. No one should be using that intentionally.
If you're an ANSI application and you cre... |
3,783,368 | 3,783,391 | Linking error while using Visual Studio 2005(VC8) | I am getting a bunch of linking errors while trying to link the release version of an executable(debug version does not have the same issue). Comparing the command line for the link does not reveal any issues.
there are broadly 2 types of errors neither of which I can get a handle on.
The first kind complains about a u... | From the errors it looks like you are not including the CRT as one of your linked libraries. Here is a link to the different CRT lib's offered in Visual Studio 2005. Choose the one which is most appropriate and make sure it's in the list of lib's to link against
http://msdn.microsoft.com/en-us/library/abx4dbyh(VS.80... |
3,783,713 | 3,783,742 | Executing a method on ui thread due to an event on background thread | I've got a background thread that is polling a server. When there's data, I want to handle the data on the UI thread. If I store the hwnd of the main window.
How can I get a particular method static void DataHandler(void* data) to be executed on the UI thread?
I think creating a timer passing the hwnd and the function... | One thing that you could do - use an inter-thread signalling object perhaps as simple as a boolean flag. When data appears on the server polling thread, you can signal the flag. You could check for this flag in the message loop of your UI thread. Alternatively, you could just send the UI thread a custom window message.... |
3,783,842 | 3,783,869 | Converting a string to LPCWSTR for CreateFile() to address a serial port | I seem to be having a bit of a TEXT / UNICODE problem when using the windows CreateFile function for addressing a serial port. Can someone please help point out my error?
I'm writing a Win32 console application in VC++ using VS 2008.
I can create a handle to address the serial port like this:
#include <iostream>
#... | You can either use std::wstring and std::wcin, std::wcout to perform input directly in "unicode strings", or you can look into Microsoft's conversion functions.
If you go for the 1st option (recommended), you still need to use the c_str() function to gain access to a LPCWSTR value (pointer to const wchar_t).
Sample so... |
3,783,861 | 3,783,870 | "C# base class virtual function" - "override in Managed C++ ref class" | I have a .NET_4 Managed C++ ref class that I derive from a .NET_4 base class written in C#.
C# base class:
namespace Core
{
public class ResourceManager
{
public class _Resource
{
public virtual void Delete() {}
}
}
}
Managed C++ class:
namespace Input.DI
{
public ref class Mouse : ResourceMa... | You put override after the function signature.
//MANAGED C++ CLASS
namspace Input.DI
{
public ref class Mouse : ResourceManager::_Resource
{
public:
virtual void Delete() override {}
};
}
|
3,783,905 | 3,783,932 | Inside random() function - How is it implemented? | We commonly use random() function to create random numbers in C++.
The use of void srand (unsigned int seed) would improve the results since it would generate random numbers depending on the value of seed.
Can anyone tell me how the random function is actually implemented?
| Here is a detailed description of the algorithm used in the GNU C library's random() function.
Basically:
#include <stdio.h>
#define MAX 1000
#define seed 1
main() {
int r[MAX];
int i;
r[0] = seed;
for (i=1; i<31; i++) {
r[i] = (16807LL * r[i-1]) % 2147483647;
if (r[i] < 0) {
r[i] += 2147483647... |
3,783,907 | 3,783,948 | error: request for the member 'query' in connection which is non-class type ' MYSQL*' | // todo: create the connection here
// Construct the query string. You were already doing this in your code
std::ostringstream query_builder;
query_builder << "select pipe_id from pipe where version_id='" << id << "'";
// Convert the ostringstream to a string
std::string query_string = query_builder.str();
// Const... | connection is a pointer; you need to use the -> operator:
connection->query(query_string)
|
3,784,035 | 3,784,065 | unable to determine cause of "no match for 'operator<'" compilation error | I am using CodeSourcery's implementation of the vector signal image processing library (vsipl++). I have written a function that is supposed to return [I + a*A]^-1 B, where I is the identity matrix, and A and B are compatible square matrices, as follows:
namespace vsipl {
template< class T1, class T2, class O1, class... | try
ld.template solve< mat_ntrans >
explanation, because the same thing made me crazy
|
3,784,114 | 3,784,135 | How to pass optional arguments to a method in C++? | How to pass optional arguments to a method in C++ ?
Any code snippet...
| Here is an example of passing mode as optional parameter
void myfunc(int blah, int mode = 0)
{
if (mode == 0)
do_something();
else
do_something_else();
}
you can call myfunc in both ways and both are valid
myfunc(10); // Mode will be set to default 0
myfunc(10, 1); // Mode will be set to... |
3,784,167 | 3,784,193 | C++ Use secant method to solve function | I have a school problem but I do not understand what it actually asks. Any of you have an idea what it's really asking for? I don't need code, I just need to understand it.
This is the problem:
Construct a computer program that uses the Secant method to solve the problem:
f(x) = (1+x) cos( sin(x)3 ) - 1.4 = 0
St... | You are supposed to use the Secant Method: http://en.wikipedia.org/wiki/Secant_method
Follow the method as described in the article. It is an iterative method much like Netwon's method. You'll need to make a function to evaluate x(n+1) given x(n) and iterate it until your margin of error is less than specified.
The cod... |
3,784,229 | 3,784,739 | Elegant way of overriding default code in test harness | Let's say I have the following class:
class Foo
{
public:
Foo()
{
Bar();
}
private:
Bar(bool aSendPacket = true)
{
if (aSendPacket)
{
// Send packet...
}
}
};
I am writing a test harness which needs to create a Foo object via the factory pattern (i.e... | You want Bar to send a packet in ordinary operation, but not in testing. So you will have to have some code which runs when you call Bar during testing, even if it's an empty function. The question is where to put it.
We can't see the code inside the if(aSendPacket) loop, but if it delegates its work to some other clas... |
3,784,239 | 3,784,250 | a simple getch() and strcmp problem | I have this simple problem that gets an input from the user using a function then checks if the input is 'equal' to the "password". However, strcmp would never return my desired value, and the culprit is somewhere in my loop that uses getch() to take each character separately and add them to the character array. I foun... |
Your char array password does not
have a terminating null char.
You need to ensure that you don't
stuff more than 8 char into
password
Also c++ should be ctr++
.
do {
// stuff char into password.
ctr++;
}while(c != 13 && ctr <8);
password[ctr] = 0;
|
3,784,411 | 3,784,463 | C++: Sum of all node values of a binary tree | I'm preparing for a job interview. I was stuck at one of the binary tree questions:
How can we calculate the sum of the values present in all the nodes of a binary tree?
| The elegant recursive solution (in pseudo-code):
def sum (node):
if node == NULL:
return 0
return node->value + sum (node->left) + sum (node->right)
then just use:
total = sum (root)
This correctly handles the case of a NULL root node.
And if you want to see it in action in C++, here's some code usin... |
3,784,553 | 3,784,671 | How do I read Registry Key Value | I am Creating the Registry Key using following code:
LPCTSTR lpNDS= TEXT("SOFTWARE\\myKEY");
if(OK==ERROR_SUCCESS)
{
MessageBox ( NULL, "Success",
_T("SimpleShlExt"),
MB_ICONINFORMATION );
}
else
{
MessageBox ( NULL, "... | You can try something like :
TCHAR szValue[TEMP_STR_SIZE] = {0};
DWORD dwStorageSize = TEMP_STR_SIZE;
LPBYTE lpStorage = reinterpret_cast<LPBYTE>(szValue);
// In case of registry value retrieval failure
if (ERROR_SUCCESS != RegQueryValueEx(hRegKey, _T("NDS"), 0, 0, lpStorage, &dwStorageSize))
{
// Prompt error
}
... |
3,784,652 | 3,784,718 | Why does GCC allow private nested template classes/structs to be visible from global template functions? | I don't understand why in the following code, I am allowed to create the function print_private_template while the compiler complains about print_private_class:
#include <cstdio>
class A
{
private:
template <unsigned T>
struct B
{
};
struct C
{
};
pub... | Comeau does give an error (when you comment out the print_private_class function and its call in strict C++03 mode.
ComeauTest.c(31): error: class template "A::B" (declared at line 7) is inaccessible
void print_private_template(const A::B &ab)
^
detected during ... |
3,784,804 | 3,784,856 | Meaning of C++0x auto keyword, by example? | auto a = (Foo<T>*)malloc(sizeof(Foo<T>));
auto *b = (Foo<T>*)malloc(sizeof(Foo<T>));
I don't think it's important that templates are there, but the question is: are a and b of the same type?
g++ -std=c++0x -Wall (4.4) doesn't give any errors or warnings, but I haven't run the program so I don't know if it does the sam... |
are a and b of the same type?
Let's find out, shall we?
#include <cstdlib>
#include <type_traits>
template <typename T>
struct Foo
{
T member;
};
template <typename T>
void test()
{
auto a = (Foo<T>*)malloc(sizeof(Foo<T>));
auto *b = (Foo<T>*)malloc(sizeof(Foo<T>));
static_assert(std::is_same<decl... |
3,784,812 | 3,784,959 | Terminating multi-line user input? | having a bit of a problem with a recent project. The goal here is to be able to input several lines of text containing a date in mm/dd/yyyy format followed by a whitespace and then a description of the event. I've accomplished actually allowing for multiple lines of text input (I think), but now I'm not exactly sure ho... | One way to accomplish this is to have the user press Ctrl-D to signify the End Of File. You will have to check for the end of file in your loop.
while ((i < MAX) && (!cin.eof()) {
cin.getline(temps, 100);
vec[i] = temps;
i++;
}
This method has the additional benefit that a text file can be presented to the pr... |
3,784,996 | 3,785,121 | Why does left shift operation invoke Undefined Behaviour when the left side operand has negative value? | In C bitwise left shift operation invokes Undefined Behaviour when the left side operand has negative value.
Relevant quote from ISO C99 (6.5.7/4)
The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, red... | The paragraph you copied is talking about unsigned types. The behavior is undefined in C++. From the last C++0x draft:
The value of E1 << E2 is E1
left-shifted E2 bit positions; vacated
bits are zero-filled. If E1 has an
unsigned type, the value of the result
is E1 × 2E2, reduced modulo one more
than the max... |
3,785,048 | 3,785,344 | Should my API use nonmember functions to act on an object, or make the functions public functions of the object? | Recently I have learnt of the many benefits (including beautiful looking code) of OOP.
So, now I am trying to write a small physics API for my personal use, perhaps to be put in a few little games. This is mainly because I like to practice coding, and I like my physics.
But the thing is, many APIs have an interface lik... | An API can look any way you want it to. If you want to make a C++ API, then you can use member functions as much as you like. With the Win32 API, Microsoft had to make something that was accessible from C (and a variety of other languages) as well as C++, so they had to express everything using features that are univer... |
3,785,096 | 3,794,176 | How to prevent duplicated resource ID in different plugins? | In MFC C++, When we add a new resourcein a EXE, says string, it will generate an ID automatically:
#define ID_SHOW_OUTPUT 10313
When it has a plugin(DLL) which has the similar ID, it will cause undefined behavior after trigerred.
To play safe, I tried to define the my own private ID:
#define ID_SHOW_OU... |
Check this add-in. It gives you a higher control over resource ids.
As Luke commented, there should not be problems using DLLs with duplicte resource ids. Only one resource module is active at a time using AfxSetResourceHandle
Setting Command IDs to arbitrary UINT values (In your question you assigned WM_APP + 6 to a ... |
3,785,149 | 3,785,242 | Type conversion for function parameters | class A{
};
class B{
public:
B();
B(const &A);
};
void foo(A &a){
}
int main(){
B b;
foo(b); //error: invalid initialization of reference of type ‘A&’ from expression of type ‘B’
return 0;
}
In the above code, I have a compilation error
error: invalid initialization of reference of type ‘A&’ from... | There are many options... hard to know what to recommend without understanding what you're program is attempting. The little insight we're given into the logical relationship between A and B is:
only one of B's constructor's requires a non-const reference to an A object
foo() is intended to work with either A or B
t... |
3,785,163 | 3,787,872 | CFile::osNoBuffer flag causes exception when writing to file | (WINAPI create file - WINAPI write file)
Flag used in winapi (FILE_FLAG_NO_BUFFERING) works fine, when I use winapi functions to write the file.
(WINAPI create file - CFile - write file)
In this situation the error also had occured, but it was because of absent file name in CFile object, that was created from the file... | See this discussion of file buffering on MSDN.
Opening the file with the flag CFile::osNoBuffer, or passing the flag FILE_FLAG_NO_BUFFERING to CreateFile, is quite a special way of writing to the file. It requires that all buffers you use to write to the file are aligned to a sector boundary in memory, and also that yo... |
3,785,366 | 3,785,388 | How-to ensure that compiler optimizations don't introduce a security risk? | I have to write a Windows service that handles at some point confidential data (such as PIN codes, passwords, and so on). Those informations are needed for a very short amount of time: usually they are sent almost immediately to a smart card reader.
Lets consider this piece of code:
{
std::string password = getPasswo... | Yes, your concerns are legitimate. You need to use specifically designed function like SecureZeroMemory() to prevent optimizations from modifying your code behavior.
Don't forget that the string class should have been specifically designed for handling passwords. For example, if the class reallocates the buffer to hold... |
3,785,558 | 3,785,571 | C++ access specifiers, too few? | As far as i know, there're only 3 access-specifiers in C++: private, public, protected
With these 3 access-specifiers, how can i make a method usable to the classes in the project but unusable to the "foreigners" ??(like internal and public in C#)
| C++ does not know what a project is.
C++ knows about classes, where it offers the three access specifiers you mentioned.
C++ knows about translation units, where it offers two access specifiers: internal and external linkage.
Edit: About internal and external linkage, this is related to whether a symbol will be seen ou... |
3,785,582 | 3,785,676 | How-to write a password-safe class? | This question follows a suggestion made by @sharptooth in this related question.
Can std::string be tweaked so that it becomes password-safe ?
If not, what would be the guidelines to write a password-handling class (thus a class that takes big care about what it writes to memory and clears it before destruction) ?
| Yes, first define a custom allocator:
template <class T> class SecureAllocator : public std::allocator<T>
{
public:
template<class U> struct rebind { typedef SecureAllocator<U> other; };
SecureAllocator() throw() {}
SecureAllocator(const SecureAllocator&) throw() {}
template <class U> SecureAllocator(c... |
3,785,646 | 3,785,679 | C++ template type that can be stored in a std::map and then exposing the map publicly | I have a class myclass that has a private member param_map
class some_class {
private:
std::map<std::string,std::shared_ptr<parameter> > param_map;
};
I want to expose this map to allow other classes, I have already created add, delete, get parameter methods, which do, what you think. But I would like to expose t... | Q1: You can expose an iterator that iterates over the map, just like std::map does.
Q2: You can use 3 different maps, or use boost::any to store the value. If you want to avoid boost, you can store void* in place of boost::any (but I would usually not go the void* way -- I would rather use the required parts of boost)... |
3,785,789 | 3,785,825 | What is the meaning of "qualifier"? | What is the meaning of "qualifier" and the difference between "qualifier" and "keyword"?
For the volatile qualifier in C and we can say that volatile is a keyword, so what is the meaning of "qualifier"?
| A qualifier adds an extra "quality", such as specifying volatility or constness of a variable. They're similar to adjectives: "a fickle man", "a volatile int", "an incorruptible lady", "a const double". With or without a qualifier, the variable itself still occupies the same amount of memory, and each bit has the sam... |
3,785,798 | 3,789,617 | Does using "pointer to volatile" prevent compiler optimizations at all times? | Here's the problem: your program temporarily uses some sensitive data and wants to erase it when it's no longer needed. Using std::fill() on itself won't always help - the compiler might decide that the memory block is not accessed later, so erasing it is a waste of time and eliminate erasing code.
User ybungalobill su... | The compiler is free to optimize your code out because buffer is not a volatile object.
The Standard only requires a compiler to strictly adhere to semantics for volatile objects. Here is what C++03 says
The least requirements on a conforming implementation are:
At sequence points, volatile objects are stable in the... |
3,785,808 | 3,822,635 | Can static allocated memory become invalid during static deinitialization? | Say I have defined a variable like this (C++):
static const char str[] = "Here is some string data";
And I have a statically allocated class instance which references this array in its destructor, can this go wrong? E.g. could the str variable somehow get invalid?
class A {
~A() {
cout << str << endl;
}
};
stati... | Okay I tried to read the C++ standard myself to find some answers. I see from the answers I get that there is a lot of confusion about difference between constructing an object and allocating it.
From the standard:
3.6.2
Initialization of non-local objects
Objects with static storage duration
(3.7.1) shall be zero... |
3,785,829 | 3,785,845 | MFC Combobox Add A-Z Drives? | I have a MFC Combobox i want to add A-Z drives to my combox at runtime
Currently i am adding like this
m_cmbdrive.AddString("A:");
m_cmbdrive.AddString("B:");
m_cmbdrive.AddString("C:")
upto
m_cmbdrive.AddString("Z:");
But it seems not to be gud approach .
Any modularlize code if any body can help on... | char drive[3];
drive[1]=':';
drive[2]='\0';
for (drive[0]='A';drive[0]<='Z';drive[0]++)
{
m_cmbdrive.AddString(drive);
}
Of course, you should check if drive is available at all before adding it into the combo, et cetera.
|
3,785,931 | 3,786,384 | Keeping memory usage within available amount | I'm writing a program (a theorem prover as it happens) whose memory requirement is "as much as possible, please"; that is, it can always do better by using more memory, for practical purposes without upper bound, so what it actually needs to do is use just as much memory as is available, no more and no less. I can figu... | I think the most useful and flexible way to use all the memory available is to let the user specify how much memory to use.
Let the user write it in a config file or through an interface, then create an allocator (or something similar) that will not provide more than this memory.
That way, you don't have to find statis... |
3,786,134 | 3,786,209 | Access specifiers and virtual functions | What are the rules for accessibility when virtual functions are declared under 3 different access specifiers specified by C++(public, private, protected)
What is the significance of each? Any simple code examples to explain the concept will be highly useful.
| Access specifiers apply in the same way as they would to any other name during name lookup. The fact that the function is virtual does not matter at all.
There is a common mistake which sometimes happens with respect to virtual functions.
If name lookup determines a viable function to be a virtual function, the access... |
3,786,151 | 3,786,636 | Beautify C++ code to add brackets to conditional statements | How can I beautify C++ code to add brackets to conditional statements? What I need to do is change:
if ( myCondition )
setDateTime( date, time );
to
if ( myCondition )
{
setDateTime( date, time );
}
but I've got to do this hundreds of times. I've used AStyle but I couldn't find how to do this with it.
Apart f... | static inline void setDateTime(date, time) { setDate(date); setTime(time); }
Regarding the if: does the astyle option --add-brackets not work for you, combined with brackets=break? When I've used astyle, I've found it difficult to get it to do exactly what I want. So if you're going to use it at all, it's easiest to de... |
3,786,191 | 3,786,302 | Do I need a visitor for my component? | I'm trying to do a small and simple GUI in C++ (with SDL). I'm experimenting with the Composite pattern to have a flexible solution.
I've got a Widget class, with Component objects : for instance, there is a PaintingComponent ; if I want to draw a box, I'll use a PaintingBoxComponent, that inherits from the PaintingCo... | If you plan to change graphic system later, you could implement this pattern. Visitor goes to root node, then recursively to all children, drawing them on some surface (known only to Visitor itself). You can gather "display list" with that, then optimize it before drawing (for example, on OpenGL apply z-sorting (lower ... |
3,786,201 | 3,787,188 | How to parse date/time from string? | Input: strings with date and optional time. Different representations would be nice but necessary. The strings are user-supplied and can be malformed. Examples:
"2004-03-21 12:45:33" (I consider this the default layout)
"2004/03/21 12:45:33" (optional layout)
"23.09.2004 04:12:21" (german format, optional)
"2003-02-11... | Although I don't know how to format a single-digit month input in boost, I can do it after the two-digit edit:
#include <iostream>
#include <boost/date_time.hpp>
namespace bt = boost::posix_time;
const std::locale formats[] = {
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
std::loca... |
3,786,212 | 3,805,001 | Effective testing in C++ with stubs and mocks? (possible?) | I'm looking for some style advice for testing this piece of (Objective-)C++ code, I bracketed the Objective part, as I don't think it should have any bearing on this test.
class Probe
{
public:
bool playing();
}
bool Probe::playing()
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
iTunesApplic... | So, I found my solution, after stumbling upon a remarkably well endowed list at wikipedia of C++ testing frameworks, I stumbled upon GoogleTest and the Google C++ Mocking Framework. Which fulfills all my requirements, whilst it's a little trickier to use than the Ruby counterparts, it is equally well featured.
One thin... |
3,786,221 | 3,786,306 | C++ structure: more members, MUCH slower member access time? | I have a linked list of structures. Lets say I insert x million nodes into the linked list,
then I iterate trough all nodes to find a given value.
The strange thing is (for me at least), if I have a structure like this:
struct node
{
int a;
node *nxt;
};
Then I can iterate trough the list and check the... | I must be related to memory access. You speak of a million linked elements. With just an int and a pointer in the node, it takes 8 bytes (assuming 32 bits pointers). This takes up 8 MB memory, which is around the size of cache memory sizes.
When you add other members, you increase the overall size of your data. It does... |
3,786,360 | 3,786,481 | Confusing Template error | I've been playing with clang a while, and I stumbled upon "test/SemaTemplate/dependent-template-recover.cpp" (in the clang distribution) which is supposed to provide hints to recover from a template error.
The whole thing can be easily stripped down to a minimal example:
template<typename T, typename U, int N> struct X... | ISO C++03 14.2/4:
When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword t... |
3,786,394 | 3,786,516 | Generating C++ code at runtime, compiling and running it | is there a multiplatform c++ compiler that could be linked into any software ?
Lets say I want to generate c++ code at runtime, compile it and run it.
I'm looking for a compact solution (bunch of classes), preferably LGPL/BSD licence :)
As far as I know it can be done in Java and c#. What about c++ ?
| I'd drop C++ altogether and use Google V8. If you wanted to use C++ because the people using your app only know this, they should have no difficulties going to javascript.
And it's damn fast. And Javascript is a cool language too.
|
3,786,616 | 3,786,845 | Templates Non Type Parameters+ Lvalue/Rvalue |
C++03 $14.1/6 - "A non-type
non-reference template-parameter is
not an lvalue."
C++0x $14.2/6- "A non-type
non-reference template-parameter is an
rvalue."
Is there any specific rationale behind rewording it?
| With the new C++0x wording, an expression can either be an lvalue, xvalue or prvalue. The first two are summed as glvalue and the latter two as rvalue.
The C++0x text says prvalue, not rvalue. Since neither "not lvalue" nor "rvalue" will say definitely what it is.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.