question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
7,254,131 | 7,254,598 | Is it possible to use boost::filter_iterator for output? | I am using std::transform with an std::back_inserter to append elements to an std::deque. Now the transformation may fail and will return a invalid object (say an uninitialized boost::optional or a null pointer) in some cases. I would like to filter out the invalid objects from getting appended.
I thought about using... | I suggest using boost range (algorithms & adaptors) for ease of use, you'd write:
boost::copy(
data | transformed(makeT) | filtered(validate) /* | indirected */,
std::back_inserter(queue));
Here is a complete working example of that:
#include <boost/range.hpp>
#include <boost/range/adaptors.hpp>
#include <boo... |
7,254,477 | 7,260,429 | extracting strings from JavaScript code | Using embedded SpiderMonkey in my C++ application I would like to extract all the strings from JavaScript code. JavaScript code looks something like this:
var foo = "something";
var space = " ";
var bar = foo + space + "beautiful";
C++ code looks like this:
char *script = "var foo = \"something\"; var space = ... | Since bar is property of global object, after the JS_EvaluateScript() I can use JS_GetProperty() function, something like this
JS_GetProperty(cx, global, "bar", &rval);
JSString *str = JS_ValueToString(cx, rval);
printf("%s\n", JS_EncodeString(cx, str));
|
7,254,688 | 7,255,025 | How to get rid of integer overflow warning? | In my C++ code I have an expression where I multiply unsigned long integer to an int to assign the result to unsigned long int. I am getting a warning as 'overflowed returned value'. I tried to cast the int to unsigned long but it did not help. Any suggestions...
The expression is something like this-
uint64_t size = 0... | The following should do the job:
size = value*(uint64_t)(unsigned int)pageSize;
|
7,254,698 | 7,257,081 | Regarding 2-d array initialisation in C++ | I get mixed responses for this question on 2-d array initialization in C++.
Here's the scenario:
class MyClass {
private:
static char my2dArray[10][20];
};
char MyClass::my2dArray[10][20] = {{0}};
Now does this initialize all elements of this array with 0?
Also, if I have the following type definition:
type... |
class MyClass {
private:
static char my2dArray[10][20];
};
char MyClass::my2dArray[10][20] = {{0}};
Now does this initialize all elements of this array with 0?
Sort of.
Recall that the elements of your array are not char, but char[10] (which cannot be 0).
What you're doing here is initialising the outer ar... |
7,254,879 | 7,254,943 | How to declare and instantiate a variable in Qt? | At first I want to apologize for this stupid question, but I'm fairly new to Qt, so forgive me ;)
I'm drawing QPixmaps. But for performance issues I only want to load my QPixmaps once to use them over and over again. At the moment I'm loading them always when update is called, but it should be possible to load them onl... | Qt is a C++ library, so you just write c++ code:
Header:
class foo : public QWidget {
public:
foo(QWidget *parent = 0);
private:
QPixMap *bar;
};
Source:
foo::foo(QWidget *parent) : QWidget(parent) {
bar = new QPixMap("bar.png");
// Some error checking...
}
|
7,255,236 | 7,255,370 | Is there a cross-platform solution in C++ for creating an unique process? | I need to make my program only one process on several platforms. I have known it can be solved with mutex on Windows, but I don't know how are other plat-forms like Linux. Mutex is not a part of C++ 03 standard though it is in C++ 0x standard. I have to wait a long time before compilers support C++ 0x well. Can boost's... | Have a look at boost's interprocess library: http://www.boost.org/doc/libs/1_47_0/doc/html/interprocess.html
I have used a named_mutex http://www.boost.org/doc/libs/1_47_0/doc/html/boost/interprocess/named_mutex.html to make sure only one instance of my program was running.
|
7,255,281 | 7,256,320 | Necessity of forward-declaring template functions | I recently created this example code to illustrate C++11 variadic template function usage.
template <typename Head, typename... Tail> void foo (Head, Tail...);
template <typename... Tail> void foo (int, Tail...);
void foo () {}
template <typename... Tail>
void foo (int x, Tail... tail)
{
std :: cout << "int:" << x... | GCC (and Clang) are right. MSVC would get it wrong because it does not implement the look-up correctly.
There is, it seems, a misunderstanding from your colleague. The rules for look-up are:
the Base template function need be declared before it is called from a definition
the Specialized template function need be decl... |
7,255,359 | 7,259,688 | Copy private vectors between classes | Vectors if are data of a class should be assigned as private member of that class.
The class should provide the methods to access the vector methods needed.
Now I have my class Snake which encapsulate a snake for the classic game.
typedef std::vector<Polygon4>::const_iterator const_iterator;
enum directions{UP, DOWN, R... | If you already have a function
void add_IntToP_list(Polygon4 cube){p_list.push_back(cube););
for adding a single element, you can add another overload for adding a range of elements
void add_IntToP_list(vector<Polygon4>::const_iterator first,
vector<Polygon4>::const_iterator last)
{ p_list.inse... |
7,255,379 | 7,255,637 | Trailing return types, decltype and const-ness | I was merily experimenting with the new trailing return types, where I hit a problem with this (simplified) code
#include <list>
class MyContainer{
std::list<int> ints;
auto begin( ) -> decltype(ints.begin())
{
return ints.begin();
}
auto begin( ) const -> decltype(ints.begin())
{
return ints.beg... | You are correct, this is a bug. According to N3291, section 5.1.1, paragraph 3:
If a declaration declares a member function or member function template of a class X, the expression this is a prvalue of type “pointer to cv-qualifier-seq X” between the optional cv-qualifer-seq and the end of the function-definition, membe... |
7,255,441 | 7,256,310 | Boost::threads work in debug, don't in release | I started doing threads about an hour ago and am having some trouble where the debug mode does what I expect and the release mode cashes.
Debug
g++ -c -g -MMD -MP -MF build/Debug/GNU-Linux-x86/foo.o.d -o build/Debug/GNU-Linux-x86/foo.o foo.cpp
Whatever 2222222222
Release
g++ -c -O2 -MMD -MP -MF build/Release/G... | You have not initialized inside array. Add initialization code to foo::foo()
foo::foo()
{
inside = new int[NUMINSIDE];
for (int i = 0; i < NUMINSIDE; i++)
{
inside[i] = 0;
}
}
It works only in debug because it is undefined behavior.
|
7,255,457 | 7,255,540 | C++ to .NET : I need help with understanding C++ code to convert it to .NET | C++ code is :
unsigned short* ui=(unsigned short*)&buf[110];
CountDev=ui[0];
buf is byte[] and CountDev is unsigned int
(BCB6 Compiler x86)
My try is :
F#
...CountDev = System.BitConverter.ToInt32( [| arrayRead.[110]; arrayRead.[111] |] , 0 )
C#
...CountDev = System.BitConverter.ToInt32( [arrayRead[110... | I would just do this to simply concatenate the two bytes and putting it into an int:
UInt32 CountDev = (UInt32)arrayRead[111] << 8 | (UInt32)arrayRead[110];
since you just need the least significant two byte, and int is 4 byte long (the most significant or sign bit is not touched), you can also use a signed int:
int C... |
7,255,582 | 60,277,816 | Drag and drop with Qt: Knowing target application on hover - is it possible? | I'm currently exploring the possibilities of drag-and-drop from a Qt application, into an unknown target application. The question is whether it is possible for the Qt application to receive information about the application that is about to receive the drop (e.g. process name, or title).
A (made up) example could be d... | You can add several data types to your drag mime data. While creating dragable data you can put image and points data (with proper mime-type) and each application will decide what data it accepts and how to interpret it.
For more details check https://doc.qt.io/qt-5/dnd.html#dragging
|
7,255,619 | 7,255,650 | iterators in Unordered (or Hash) Maps | As far as I understand, Hashmaps are preferable to standard maps because you can find elements in close to O(1) time. This is done by using a hash or the key as an array lookup. We then resolve any collisions and pull out the value.
This works great for lookup, but if our array-space into which we do the hash lookup is... | Unless there's a parallel structure (for example a linked list as in a LinkedHashMap) it can't: iteration will need to check each bucket for content.
So if your buckets are very sparsely populated, this can become a factor. That's one of the reasons why you don't want to choose a bucket count that is too high (the bigg... |
7,255,684 | 7,256,046 | indentation for method chaining | Suppose I've a very long method chaining
object.SetA(123).SetB(234).SetC(345) ...
what's the best indentation? All compilers supports them?
object.
SetA(123).
SetB(234).
SetC(345) ...
or
object
.SetA(123)
.SetB(234)
.SetC(345) ...
| Assuming that we're talking about method chaining on the same object (each function retuns *this), how about:
object.setA().setB().setC();
object.setD().setE().setF();
Long lines aren't just bad because your screen isn't wide enough to contain them. If that's all there was to it, just buy a bigger monitor or reduce th... |
7,256,436 | 7,304,634 | Forward declarations of unnamed struct | Bounty question: So, these two Foos aren't the same thing. Fine. The second form is given in a library. How do I forward-declare it given that I can't change it?
I always thought C and C++ allowed repeated declarations provided that there were no repeated definitions. Then I came across this problem when trying to wri... | typedef-ing anonymous struct is a practice that pre-dates C++03 and is mainly oriented to retain compatibility with pre-C99 compilers.
Given that this is 2011, and that both C++ and C are changed, I wonder why there is no more up-to-date version of such a library!
If it is not in development anymore, you cannot "leave"... |
7,256,499 | 7,256,655 | wxWidgets wxConfBase Write very slow | I'm using wxConfBase to save the data of my text box. (windows)
config = new wxConfig(wxT("soft"));
config->Write(wxT("COM"),temp_port->GetValue());
config->Write(wxT("SQL_HOST"),mainset_sql_host->GetValue());
config->Write(wxT("SQL_DB"),mainset_sql_db->GetValue());
config->Write(wxT("SQL_LOGIN"),mainse... | For given name "soft":
Windows: wxConfig writes to HKEY_CURRENT_USER\Software\soft.
Linux: wxConfig creates hidden .soft file in home directory.
Using wxConfig in both OS, I didn't have any performance problems. Try to investigate more, knowing where this information is saved.
|
7,256,530 | 7,256,575 | Singleton - Protected vs Private Constructor | When designing singletons, why is the constructor made protected and not private? This is based on what I've seen over the web.
We want to control the number of instances made of that class, fair enough, but why protected? Wouldn't private do the trick as well?
| Using singletons is bad. Period.
That said, the constructor can be private, no problem. But what if you want to derive another singleton from your singleton(as if having one singleton wasn't bad enough)? In that case the derived class needs access to the base singleton constructor.
|
7,256,647 | 7,259,271 | Problem with deque: map<..., deque<> > fails, but vector and list aren't? | I have a code:
typedef map<Coordinate3D, deque<someClass > > someMap;
someMap *newEM;
someMap::iterator iter;
//...
(*newEM)[iter->first].insert((*newEM)[iter->first].end(),
iter->second.begin(), iter->second.end());
that intended to merge two someMap. But there is a problem that crashes p... | You have defined a copy constructor in someClass but no assignment operator.
As soon as something "interesting" happens to the objects, you will leak the old values and then have two objects pointing to the same complexClass. When the first of those deletes its pointer, all the copies will have invalid pointers!
Tryin... |
7,257,011 | 7,257,148 | Is Visual C++ intellisense "smarter" than the compiler | I have the following scenario.
I have a base class from which a class derives. Everything appears good however, every time I hover my mouse cursor over an inherited member of the base class, the intellisense shows it fine, EG BaseClass::SomeMember. However, when I try to compile, the compiler shows various errors(they... | If this is VC2010, then yes, in a sense Intellisense is smarter.
They switched to using EDG's compiler frontend for IntelliSense, and that is a stricter, more standards-compliant compiler than Microsoft's own one. So there are cases where IntelliSense and the "real" compiler disagrees.
Sometimes IntelliSense is wrong b... |
7,257,144 | 7,257,307 | When to use std::forward to forward arguments? | C++0x shows an example of using std::forward:
template<class T>
void foo(T&& arg)
{
bar(std::forward<T>(arg));
}
When is it advantageous to use std::forward, always?
Also, it requires to use && in the parameters declaration, is it valid in all cases? I thought you had to pass temporaries to a function if the functi... | Use it like your first example:
template <typename T> void f(T && x)
{
g(std::forward<T>(x));
}
template <typename ...Args> void f(Args && ...args)
{
g(std::forward<Args>(args)...);
}
That's because of the reference collapsing rules: If T = U&, then T&& = U&, but if T = U&&, then T&& = U&&, so you always end up w... |
7,257,218 | 7,257,501 | What is thare any special boost\std container for trees? | So I want to store pairs string-path <-> my_file_object in such container with expected total object size 100 000.
I need to have search by absolute path to get an object for example I could search for a/b/c/file.h)
I need to be capable to list all item names in folder like folder a/b/c/ contains files file.h, file.cp... | What requirements do you have that rule out std::map? As far as I can see it will work well here:
typedef std::map<std::string,file_object_t> paths_t;
paths_t paths;
//I need to have search by absolute path
paths_t::iterator fileIterator = paths.find("a/b/c/file.h");
if( fileIterator != paths.end() ) {
...
}
//I ... |
7,257,339 | 7,289,816 | QT C++ - OpenSSL AES - EVP.h | I've been trying to use OpenSSL with QT in the past few days but the documentation and the examples are rare or none.
Anyway, I come up with this code:
void qkCrypto::AES_CBC(const unsigned char *string, const unsigned char *key, const unsigned char *iv)
{
int outlen;
unsigned char *out;
EVP_CIPHER_CTX ct... | I've new code now almost perfect.
QByteArray qkCrypto::encrypt_AES_CBC(QByteArray string, QByteArray key, QByteArray ivv)
{
char mykey[EVP_MAX_KEY_LENGTH] = { 0 };
strcpy(mykey,key.constData());
char iv[EVP_MAX_IV_LENGTH] = { 0 };
strcpy(iv,ivv.constData());
char ciphertext[1024];
const EVP_... |
7,257,367 | 7,257,408 | expected unqualified-id before numeric constant in STK code | I included the The Synthesis ToolKit in C++ (STK) from stanford into my project and when I try to build I get the following error:
error: expected unqualified-id before numeric constant
in the second line written here, from the STK.h: (in the part where they declare their namespace)
const StkFloat PI = 3.1415926535897... | My guess is that some evil header defines PI as a macro.
Either find and destroy that header, or put #undef PI before including the toolkit header.
|
7,257,476 | 7,257,526 | How do I send or save a function and recv or restore a function and execute it in C++? | Is there any way I can send or save a function as file? I want to do this in C++ on a Windows platform.
I assume that there is some convention between reader and sender or saver
Is it OK if I send like below?
server side:
label1:
int func1(int somevar){
int a = 1;
return somevar+a;
}
label2:
send(sockfd, label... | No, there's no way to do that in C++. Languages which could allow transfer of executable code include Erlang, Ruby, TCL.
Chris
|
7,257,563 | 7,257,601 | What are qualified-id/name and unqualified-id/name? | I was wondering if someone could explain there terms since I encounter them in many places. I know some basic theory about them but not sure what I know is right or wrong.
So can any one please explain these terms?
| A qualified name is one that has some sort of indication of where it belongs, e.g. a class specification, namespace specification, etc. An unqualified name is one that isn't qualified.
Read James McNellis' answer here:
What is a nested name specifier?
Given:
struct A {
struct B {
void F();
};
};
A i... |
7,257,892 | 7,258,009 | php & so error: class not found |
Possible Duplicate:
How can I use C++ code to interact with PHP?
I have the following test.php file:
<html>
<head>
<title>Personalized Hello World</title>
</head>
<body>
<?php include "/home/test.hpp";
$s= new example();
?>
</body>
</html>
the test.hpp file is:
#ifndef TEST_
#define TEST_
clas... | You are trying to include C++ code from a PHP script. The PHP interpreter is not able to parse C++ code. Only PHP code. Because is a PHP interpreter. Not a C++ Compiler. These are different languages.
As @J0HN advises, you should read that : How can I use C++ code to interact with PHP?. It explains how to write extensi... |
7,257,938 | 7,258,060 | Sending a control signal? | I am working on making a client and a server with windows, c++
the design what I decided is
server is just sending what client have to render depends on client's sending message.
sort of tiles and objects, picture, line, rectangle, circle... could be drawn on client side
and a client just receive a command from server... | Well, if you don't want to send and execute scripts, try to find some simple solution. For example, message format can be defined as:
draw file name srcX srcY width height destX destY [srcX srcY width height destX destY ...]
Some optimization may be applied, for example, you can pass only the difference between previ... |
7,257,956 | 7,258,542 | How to insert spaces in a big number to make it more readable? | I came up with this, since other examples provided on stackoverflow were in C#
string number_fmt(ulong n)
{
// cout << "(" << n << ")" << endl;
char s[128];
sprintf(s, "%lu", n);
string r(s);
reverse(r.begin(), r.end());
int space_inserted = 0;
size_t how_many_spaces = r.length() / 3;
i... | This one is different, but better is subjective. I think it's very succinct and clear what it's doing though:
string number_fmt(unsigned long long n, char sep = ',') {
stringstream fmt;
fmt << n;
string s = fmt.str();
s.reserve(s.length() + s.length() / 3);
// loop until the end of the string and u... |
7,258,198 | 7,272,864 | Sparse matrix class with parameterizable "zero" | I am doing some computations on a sparse matrix of floats in the log domain, so the "empty" entries are actually -Inf (using -FLT_MAX). I'm using a custom sparse matrix class right now but I am eager to swap in an off-the-shelf replacement.
This is in C++. My inclinations were to look at the compressed column matrice... | The solution I have currently cooked up is this. Define a class lfloat:
class lfloat {
float value;
public:
lfloat(float f=-FLT_MAX)
{
value = f;
}
lfloat& operator=(float f)
{
value = f;
return *this;
}
operator float() { return value; }
};
and use it like so:
compressed_matrix<lfloat... |
7,258,363 | 7,258,397 | Why can I call the private constructor from ?global scope? | this code compiles and runs without errors:
class foo{
static foo *ref;
foo(){}
public:
static foo *getRef(){
return ref;
}
void bar(){}
};
foo* foo::ref = new foo; // the construcrtor is private!
int main(int argc, const char *argv[])
{
foo* f = foo::getRef();
f->bar();
return 0;
}
cou... | That scope isn't global - static members are at class scope, and so their initialization expression is also at class scope.
|
7,258,977 | 7,259,033 | Question on predefined meanings for operators | In "The C++ programming language", at page 265, the author makes the following statement:
Because of historical accident, the operators = (assignment), & (address-of), and , (sequencing;
§6.2.2) have predefined meanings when applied to class objects. These predefined meanings can
be made inaccessible to general us... | This example simply shows a way to prevent yourself or other developers of the code from using operators, which can be used without having been defined in the class, because they're automatically generated (and have default meanings for the operations they represent).
The author of the example meant, that if you try to... |
7,259,010 | 7,259,121 | In a Visual Studio 2010 C/C++, what does the "Rescan Solution" operation do? | I'm trying to compile a third-party project and I'm getting a few linking issues. I'm not having much trouble fixing the minor issues but I noticed their was a "Rescan Solution" option in the context menu of the project or solution.
I clicked it but it didn't seem to do anything. What, exactly, does it do?
| This command updates out-of-date files in the project browsing database. Nothing to do with compilation/linking problems.
|
7,259,452 | 7,259,932 | Adaptors for pointer to member fields | Is there a STL method/boost class such as:
template<class S, class T>
class mem_mem : std::unary_function<T, S>
{
public:
mem_mem(S T::*_m) : m(_m) {}
S operator()(T &t) const {
return t .* m;
}
const S operator()(const T &t) const {
return t .* m;
}
private:
S T::*m;
};
It is similar to mem_fun bu... | You can use boost::bind or boost::mem_fn for this. If the member passed in is a member to a field, boost::bind acts as a functor that returns the data member.
#include <vector>
#include <boost/bind.hpp>
#include <iostream>
#include <iterator>
struct X {
X(): a(0) {};
X(int i) : a(i) {};
int a;
};
int mai... |
7,259,572 | 7,259,961 | How to get number of bytes from QFile? | I have this code:
int *size1 = new int();
int *size2 = new int();
QFile* file = new QFile("C:/Temp/tf.txt");
file->open(QFile::WriteOnly | QFile::Truncate);
file->write(str);
*size1 = file->size();
file->close();
file->open(QFile::WriteOnly | QFile::Truncate);
file->write(strC);
*size2 = file->size();
file->clo... | Keep in mind that when you write a character to a file it's probably going to be a byte, for the most part anyway.
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
char *str = "Hello";
char *strC = "Hello again!";
... |
7,260,284 | 7,260,359 | How to create threads with Win32 API? | I have written a TCP server with Win32 API and C++ but it's single-threaded. Can anyone tell me how would I go about making it multi-threaded? I imagine for every new accepted connection, I'd have to spawn a thread that takes care of it. But I have never had experience with threading in Win32. Can anyone tell me how I ... | Read the documentation of :
CreateThread Function
And you can also see an example in my answer here:
Multithreading in c++
run threads of class member function in c++
|
7,260,292 | 7,262,910 | Find swapped nodes in a BST | I am trying to write a program that can detect and print two nodes in BST that have been swapped.
In a three level tree, I reached near to the solution using this approach.
If (!AllSubTreeAreValid())
{
//Nodes swapped on same side of main root node
}
else
{
int max = getMax(root->left);
int min = getMin(root->right... | One way to think about this problem is to use the fact that an inorder walk of the tree will produce all of the elements in sorted order. If you can detect deviations from the sorted order during this walk, you can try to locate the two elements that are in the wrong place.
Let's see how to do this for a simple sorted... |
7,260,432 | 7,260,467 | Is it valid to nest a critical section? | For example, would this be valid?
CRITICAL_SECTION cs;
::InitializeCriticalSection( &cs );
::EnterCriticalSection( &cs ); // First level
::EnterCriticalSection( &cs ); // Second level
/* do some stuff */
::LeaveCriticalSection( &cs ); // Second level
::LeaveCriticalSection( &cs ); // First l... | Yes it is valid to enter the same critical section while already inside it. From the docs:
After a thread has ownership of a critical section, it can make
additional calls to EnterCriticalSection or TryEnterCriticalSection
without blocking its execution. This prevents a thread from
deadlocking itself while waiti... |
7,260,561 | 7,260,753 | Extracting the return type from an overloaded function | I want to extract the return type of a function. Problem is, there are other functions with the same name but different signature, and I can not get C++ to select the appropriate one. I know about std::result_of, but from a few tries I have concluded it suffers from the same problem as well. I have heard about a soluti... | I think that this can be done with decltype and declval:
For example: decltype(f(std::declval<T>())).
|
7,260,809 | 7,260,881 | Does a mutex still need to be released if it times-out? | Using the WaitForSingleObject Function.
If the function is called and times out, does it still need to release the mutex?
i.e. should ReleaseMutex be in position 1. or 2. if the five seconds elapse?
WaitForSingleObject(5 second time out)
{
//access shared resource
//1. - ReleaseMutex() here?
}
//2. - ReleaseMut... | No. If the call to WaitForSingleObject times out then you have not acquired the mutex, so should not release it.
i.e. you only need ReleaseMutex at position 1.
|
7,260,904 | 7,261,308 | Are efficient "repeatedly used intermediates" possible in C++ expression template programming? | Here's one thing I haven't seen explicitly addressed in C++ expression template programming in order to avoid building unnecessary temporaries (through creating trees of "inlinable templated objects" that only get collapsed at the assignment operator). Suppose for the illustration we're modeling 1-D sequences of values... | Since you obviously don't want to do the entire calculation twice, you have to cache it somehow. The easiest way to cache it seems to be for AType to be a Seq. You say This has the downside of a full intermediate variable, but that's exactly what you want in this case. That full intermediate is your cache, and canno... |
7,260,963 | 7,262,446 | Drawing a crescent shape in OpenGL | How can I draw a 2D crescent or moon shape in OpenGL? I have tried using sin and cos like how I did for drawing circles but because a crescent has a "cut" inside it, the sin and cos don't look enough. I couldn't figure out how I could do an intersection between 2 polygons either. So I'm thinking if there a mathematical... | This isn't mathematically correct, but it may be close enough to meet your needs:
void drawCrescentLine(float step,float scale,float fullness) {
float angle=0.0f;
while (angle<M_PI) {
glVertex2f(scale*sinf(angle),scale*cosf(angle));
angle+=step;
}
while (angle<(2.0f*M_PI)) {
glVertex2f(ful... |
7,261,037 | 7,261,096 | Can a C/C++ program seg-fault from reading past the end of an array (UNIX)? | I'm aware that you can read past the end of an array - I'm wondering now if you can seg-fault just by performing that reading operation though.
int someints[100];
std::cerr << someints[100] << std::endl; //This is 1 past the end of the array.
Can the second line actually cause a seg-fault or will it just print jibberi... | This is undefined behaviour and entirely depends on the virtual memory layout the operating system has arranged for the process. Generally you can either:
access some gibberish that belongs to your virtual address space but has a meaningless value, or
attempt to access a restricted memory address in which case the mem... |
7,261,145 | 7,261,222 | compiler optimization | So I have a question for you. :)
Can you tell me the output the following code should produce?
#include <iostream>
struct Optimized
{
Optimized() { std::cout << "ctor" << std::endl; }
~Optimized() { std::cout << "dtor" << std::endl; }
Optimized(const Optimized& copy) { std::cout << "copy ctor" << std::endl;... | This is known as Copy Elision and is a special handling instead of copying/moving.
The optimization is specifically allowed by the Standard, as long as it would be possible to copy/move (ie, the method is declared and accessible).
The implementation in a compiler is generally referred to, in this case, as Return Value ... |
7,261,445 | 7,261,501 | Problem understanding a pointer to a function | I'm fine with most of the program up until the signature of selectionsort where there is a pointer to a function called compare but I don't see the function anywhere in this code. I guess what I'm trying to ask is how is compare working?
// Fig. 8.20: fig08_20.cpp
// Multipurpose sorting program using function pointer... |
where there is a pointer to a function called compare
Invoid selectionSort( int work[], const int size,bool (*compare)( int, int ) ) compare is just the local name of the (last) argument. Just like work is the local name for the array(pointer actually...) you pass in as the first argument, compare is the local name o... |
7,261,515 | 7,261,702 | Error while trying to compile a DLL with a static class function in VC++ | I am trying to take some functions that I've made and tested with in a standalone application. Now that I am trying to make a DLL I am getting a few errors stating that the function has been redefined and that the return parameters don't match. This seems to be the only time I am getting these errors, I've tested it by... | Remove extern "C" around your class definition.
|
7,261,707 | 7,261,771 | How to avoid precompiled headers | I am trying to compile a simple VS program in C++ as an assignment for class. We only ever include <iostream> and I keep getting this error:
1>Assignment.cpp(15): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?
My program is l... | You can always disable the use of pre-compiled headers in the project settings.
Instructions for VS 2010 (should be similar for other versions of VS):
Select your project, use the "Project -> Properties" menu and go to the "Configuration Properties -> C/C++ -> Precompiled Headers" section, then change the "Precompiled... |
7,261,818 | 7,262,090 | Do certain exception errors occur only in the debugger? | In a program I accidentally called closeHandle() twice on a mutex handle (closing the handle that was already closed).
When running the code in the debugger, I received the exception error An invalid HANDLE was specified. as expected.
However, running the program "normally" as a stand alone (outside of the debugger) th... | The documentation states:
If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a pseudo-handle value. This can happen if you close a handle twice, or if you call CloseHandle on a handle returned by the FindFirstFile function inst... |
7,262,055 | 7,262,079 | Why does std::queue not have operator[]? | The std::queue is implemented with a deque by default. std::deque has the subscript operator, operator[], and is probably implemented with arrays. So why doesn't std::queue have operator[]?
I realize you could have a queue with a list as the underlying container. (std::queue<int, std::list<int>>.) But even if that woul... | Because the definition of queue doesn't support such interface. Queue is a FIFO data structure which means First In First Out. Queue supports enqueue and dequeue operations.
Imagine of queue as pipe : you insert data into one end and from the other end you take it out - one by one. Inserting data is called enqueue and... |
7,262,078 | 7,262,338 | How do you move between nodes of a linked list? | This is a piece of code that tries to build a linked list.
struct node {
char name[20];
int age;
int height;
node* next; // Pointer to the next node
};
node* startPTR = NULL;
void addNode_AT_END() {
node *temp1;
node *temp2;
temp1 = new node;
cout << "Enter the name : ";
cin >>... | Here is where all the magic happens:
1. temp2 = startPTR;
2. while( temp2->next != NULL )
3. temp2 = temp2->next;
4. temp2->next = temp1;
First, temp2 will point to the beginning of the list. In lines 2 and 3, you change temp2 to the next node until you reach the node where temp2->next is NULL. This node is the las... |
7,262,644 | 7,262,681 | Get the text of a combo box Win32 API C++ (NO MFC) | I am trying to setup a combo box so a user can select an option from the dropdown menu and then retrieve what the user selected using Win32 API C++ programming, not MFC. I read John's post here and I could not get anything to work. I can set the text for the combo box, but I cannot retrieve what the user selected. Here... | For the call to ComboBox_GetText the hwnd parameter must be the handle to the combo box itself, not the dialog. You can get that HWND with GetDlgItem(hwnd, IDC_COMBO1);
Also, you can't pass an uninitialized pointer to either function; you must pass a pointer to a buffer which you have created.
char buf[10];... |
7,262,708 | 7,262,762 | Do compilers usually have special optimizations for strings? | Often times you see things like
std::map<std::string, somethingelse> m_named_objects;
or
std::string state;
//...
if(state == "EXIT")
exit();
else if(state == "california")
hot();
where people use strings purely to make something more readable. The same thing could easily be achieved with something like inte... |
Can modern compilers (msvc, g++, etc.) usually employ special optimizations for these types of cases?
As far as I know, compilers don't make those kinds of optimizations. It's definitely not a "standard" optimization.
...where people use strings purely to make something more readable.
At least for your second case,... |
7,262,739 | 7,262,784 | When doing socket programming, what is the correct way to look up a domain name and then connect to it? | I've programmed networked applications, but primarily in Python.
I'm writing a C++ application and I'm a little fuzzy on exactly what the syntax should be to look up a domain name and connect to it's IP address.
Specifically, I'm not sure how to go form the result of a gethostbyname() call to a socket.
My code currentl... | Technically you should use h_addrtype rather than assume AF_INET and then interpret h_addr_list based on that type. Once you are already assuming AF_INET (both in the socket and in connect) you may as well assume that h_addr_list[0] is an in_addr as you are doing. You could check h_addrtype in case you got an AAAA re... |
7,262,753 | 7,262,836 | What happens to the resources that aren't cleaned up when you use _exit in UNIX? | I've read that you can call either exit or _exit when you wish to terminate a process in UNIX, and also that exit frees resources (the style used when we return from main) where _exit immediately terminates without cleanup.
What is the impact of closing a program with _exit with regard to the operating environment, and... | There is no difference in resources freed when exiting with _exit versus exit unless you have installed atexit handlers. Named shared memory objects, SysV IPC resources, files in the filesystem, etc. will not be destroyed on either type of exit; memory allocated to the process (in fact, its whole virtual memory space),... |
7,262,818 | 7,263,017 | If I jump out of a catch-block with "goto", am I guaranteed that the exception-object will be free'ed? | I have such code as follows
try {
doSomething();
} catch(InterruptException) {
goto rewind_code;
}
if(0) {
rewind_code:
longjmp(savepoint, 1);
}
My question is, is the exception object that is stored by the C++ runtime free'ed when I goto out of the catch block? Or is the runtime allowed to cache it until the s... | §6.6/2:
On exit from a scope (however accomplished), destructors (12.4) are called for all constructed objects with automatic storage duration...
At least as I'd read it, "however accomplished" should/does include a goto.
Edit: Okay, based on Johannes's comment, what we care about is §15.1/4:
When the last handler ... |
7,263,433 | 7,266,900 | Best code for compiling static const int = X in VS2008 and GCC | I have run into a problem while writing C++ code that needs to compile in Visual Studio 2008 and in GCC 4.6 (and needs to also compile back to GCC 3.4): static const int class members.
Other questions have covered the rules required of static const int class members. In particular, the standard and GCC require that the... | I generally prefer the enum way, because that guarantees that it will always be used as immediate value and not get any storage. It is recognized as constant expression by the compiler.
class Whatever {
enum { // ANONYMOUS!!!
value = 42;
};
...
}
If you can't go that way, #ifdef away the definition... |
7,263,473 | 7,273,671 | Why do tuples have uses_allocator but pairs don't? | While experimenting with the C++11 std::scoped_allocator_adaptor as implemented in gcc 4.7.0 so far, I noticed that C++11 FDIS defines a specialization of std::uses_allocator for tuples (20.4.2.8[tuple.traits]), but not for pairs, although for all other purposes, pairs look and act just like tuples (they have specializ... | One reason is that we want to avoid having 15 constructors (like in N3000) for a seemingly simple class like std::pair.
We have now instead got one "general-purpose" constructor
template <class... Args1, class... Args2>
pair(piecewise_construct_t,
tuple<Args1...> first_args, tuple<Args2...> second_args);
where y... |
7,263,672 | 7,263,734 | Doing enum cast to int | I've a problem on this code:
template <typename T>
void dosth(T& value,const T& default_value)
{
if (condition)
value = 10;
else
value = default_value;
}
When I call that with
enum {
SITUATION1,
STIUATION2
};
int k;
dosth(k,SITUATION1);
the compiler (g++ 4.5) says
no matching function fo... | Your problem is due to the fact that the template cannot be instantiated from the function arguments that you supply. No implicit conversion to int occurs, because there's no function to call at all.
If you cast instead of attempting to rely on implicit conversion, your program will work:
dosth(k, static_cast<int>(SITU... |
7,263,720 | 7,263,789 | Why doesn't my program catch an exception from dereferencing a null pointer? | Can some please explain why this exception isn't caught.
try {
// This will cause an exception
char *p = 0;
char x = 0;
*p = x;
}
catch (...) {
int a = 0;
}
When I run the program it dies on the line *p = x. I would expect that the catch block would cause this exception to be ignored.
I'm using th... | Structured exception handling __try and __catch will catch system faults, see:
http://msdn.microsoft.com/en-us/library/swezty51(v=vs.80).aspx
|
7,263,816 | 7,264,105 | Organizing project files in Solution Explorer in Visual Studio | I'm making my first D3D simple game. My game uses many images.
This is my organization on disk:
MyGame
|
|-Debug
|-Release
|-Assets
|-Others
|-Images
|All cpp and h fiels here
If I launch my game from Visual Studio, thr game is working. But if I launch the game from Windows (by clicking the EXE file in the Release... | Another possibility to @shelleybutterfly's answer is to always refer to images relatively, e.g. as "..\Assets\Images\abcde.bmp". Then when you deploy you could put your executable in the same kind of structure as long as the relative relationship is still the same.
e.g. Project:
MyGame
|-Debug
|-Release
|-Assets
|-Ot... |
7,263,828 | 7,263,878 | How to pass message to a thread | I need to write a sort of proxy server and my design is a little like this:
1. Socket server (using Windows Event select model). program has a listener thread listenimng for network events.
2. list of clients (currently indexed by socketid).
3. socket server accepts a new connection and then creates a new thread for ea... | Use a messaging or synchronization primitive, such as a queue, mailbox, event signal, etc.
For instance, if each thread has a queue for data to send, you would simply write to this queue. The queue must be thread safe to allow concurrent access.
|
7,263,876 | 7,406,897 | Building a Linux C++ API as a Windows DLL | I'm attempting to build the C++ Avro API as a DLL so I can use the Avro generated header files in a Visual Studio project. I'm able to build Avro in Windows using Cygwin, so the next step is to convert the Avro API into a DLL and use it along with the cygwin1.dll in my project (not entirely clear on how this would work... | I made a sample project that attempts to generate the DLL and this is what I had in my CMakeLists.txt:
PROJECT(DLLTest)
# Allow the developer to select if Dynamic or Static libraries are built
OPTION (BUILD_SHARED_LIBS "Build Shared Libraries" ON)
# Set the LIB_TYPE variable to SHARED
SET (LIB_TYPE SHARED)
#IF (BUIL... |
7,264,101 | 7,264,355 | Implementing Bentley-McIlroy three-way partitioning using STL iterators? | In their talk "Quicksort is Optimal", Sedgewick and Bentley refer to a modified version of the quicksort partitioning step called Bentley-McIlroy three-way partitioning. This version of the partition step adapts gracefully to inputs containing equal keys by always pulling out copies of the pivot element from what rema... | without substantially rewriting the core of the algorithm
That pretty much limits you to trying to hack your way around the boundary issue, so you'd need to use a custom iterator adapter, or wrap the iterator in a boost::optional or something similar so you know when its the first access.
What would be better would be ... |
7,264,283 | 7,265,121 | Relative path problem - one dir up | This is workig:
I have my exe in the same directory as Images folder;
Main:
|-Images
|-cross_ball
|-frame.bmp
|-game.exe
I'm refering to frame.bmp in my game.exe.
This path is workig good: "Images\\cross_ball\\frame.bmp"
This is not working:
Exe is in bin folder. bin folder is in the same folder as Images folder... | If "Images\cross_ball\frame.bmp" is working, then your app's current directory isn't the Images directory like you think it is. It must be one dir up for that to work. That would also explain why moving the exe to the bin directory fails.
Are you starting your app from a shortcut or in a debugger? Shortcuts and de... |
7,264,308 | 7,264,376 | C++ defensive programming: reading from a buffer with type safety | Let's say I have a class that I don't own: DataBuffer. It provides various get member functions:
get(uint8_t *value);
get(uint16_t *value);
...
When reading from a structure contained in this buffer, I know the order and size of fields, and I want to reduce the chance of future code changes causing an error:
struct ... | Don't use overloading. Why not have get_word and get_dword calls? The interface isn't going to be any uglier but at least the mistake is a lot harder to make.
|
7,264,408 | 7,264,444 | Difference between array[n] and array[]? | Is there any difference between, for example
int array[]={1, 2, 3, 4, 5};
and,
int array[5]={1, 2, 3, 4, 5};
Compiler needs to calculate number of elements by self for the first case, and that can take a some time ({...} of 1234332534 elements), so second case is efficient than the first?
| There's no difference, as long as the explicit element count between [] is the same as the number of initializers between the {}.
The question about "efficiency" is moot. The array size is determined at compile time, which means it has no impact on the efficiency of the code. And since in any case the compiler will hav... |
7,264,485 | 7,264,722 | DirectShow video playing too fast when audio pin rendering data | I'm working on a custom Windows DirectShow source filter based on CSource and CSourceStream for each pin. There are two pins - video output and audio output. Both pins work fine when individually rendered in graphedit and similar tools such as Graph Studio with correct time stamps, frame rates and sound. I'm rendering ... | I realised the problem straight after posting the question. A case of debugging by framing the question correctly.
The audio stream had completely bogus time stamps. The audio and video streams played back fine individually but did not synch at all with each other when played together.
|
7,264,679 | 7,264,706 | C++ how to call parent's friend function? | There is a Base class and a Derive class. Derive public inherit Base. The base class has implemented a friend function bool operator==(const Base& lhs,const Base& rhs) const;
I am implementing the Derive class, which also need to implement bool operator==(const Derive& lhs, const Derive& rhs) const; Now my problem is t... | Bind references to the Base subobjects, and compare them with normal operator syntax. An example:
class Base { /*...*/ };
bool operator==(const Base&, const Base&);
class Derive : public Base
{
friend bool operator==(const Derive&, const Derive&);
private:
int mem_;
};
bool operator==(const Derive& d1, cons... |
7,264,690 | 7,264,765 | wstringstream to LPWSTR | I have built up a string using wstringstream and need to assign it to a member of a struct of type LPWSTR. I try to use my_stringstream.str().c_str() but get the following compile time error:
cannot convert from 'const wchar_t *' to 'LPWSTR'
How can I do this? I have tried many different combinations of casts with ei... | Your function expects a pointer to modifiable data, i.e. wchar_t*, but the standard string class only exposes a pointer to constant. Assuming that your function may actually write to the memory, we need to provide it with a valid pointer.
An easy way to obtain a modifiable buffer is, as always, a vector:
std::vector<wc... |
7,265,157 | 7,265,173 | Is this nested array using stack or heap memory? | Say I have this declaration and use of array nested in a vector
const int MAX_LEN = 1024;
typedef std::tr1::array<char, MAX_LEN> Sentence;
typedef std::vector<Sentence> Paragraph;
Paragraph para(256);
std::vector<Paragraph> book(2000);
I assume that the memory for Sentence is on the stack. Is that right?
What about t... | There is no stack. Don't think about a stack. What matters is whether a given container class performs any dynamic allocation or not.
std::array<T,N> doesn't use any dynamic allocation, it is a very thing wrapper around an automatically allocated T[N].
Anything you put in a vector will however be allocated by the vecto... |
7,265,392 | 7,265,590 | Debug Assertion Failed | I am getting this error with my c++ code:
http://imageshack.us/photo/my-images/193/vcerror.png/
The only problem is it doesn't point me to where the problem is... I understand the string subscript is out of range but I have no idea where it could be.
I was wondering if there is anyway I am able to find where it is? I ... | Basically, you need to look at the callstack and have all your symbols setup.
I'm going to take a wild guess and suggest that you may not know how to use the "call stack" window.
In a debug session of your program and no breakpoints set, allow your program to run until it hits the assert dialog. Press "retry" to allow... |
7,265,506 | 7,265,767 | Should outside libraries be wrapped? | I have been using two libraries, SFML and Box2D, while at the same time taking great pain to ensure none of their functions or classes are exposed in the main body of my code, hiding them behind classes that serve little more than to act as a mediator between my code and the library itself. My mediators take the follo... | The problem with the wrapper technique you're describing is that your wrapper is transparent (in the true sense of that word) -- every method in the library is still visible to you through the wrapper, with the same semantics, same preconditions, etc. You can "see right through" your wrapper.
A transparent wrapper like... |
7,265,697 | 7,266,438 | Bailey–Borwein–Plouffe formula implementation in C++? | EDIT: The requirement was vague and instead of calculating the n-th digit of pi they just wanted pi to the n-th digit not going beyond floats limitation so the brute force way worked for the requirements.
I need to calculate PI the the n-th digit and I wanted to try using the BBP formula but am having difficulties. Th... | Regardless of what formula you use, you will need arbitrary precision arithmetic to get more than 16 digits. (Since "double" only has 16 digits of precision).
The Chudnovsky Formula is the fastest known formula for computing Pi and converges at 14 digits per term. However, it is extremely difficult to implement efficie... |
7,265,797 | 7,267,058 | data visibility in different shared library in linux | Suppose there is a program which will dynamically load two shared library and there is a message allocated in library A. I want to know if it is possible for library B to use that message.
Edit: Since it is just in the design stage, there is no "real code".
in shared library A:
void process()
{
msg_ptr = new message(... | (Edit): Ok, the question is somewhat confusing because the send and recv imply inter-process communication and it seems not to be the case, so:
Short answer: Yes, it does not matter which library, static or dynamic, does the allocation. It is always process-wide.
Shared library means the code is stored on disk once, bu... |
7,266,085 | 7,266,247 | How to access the addresses after i get out of the loop? | #include<iostream>
using namespace std;
struct data {
int x;
data *ptr;
};
int main() {
int i = 0;
while( i >=3 ) {
data *pointer = new data; // pointer points to the address of data
pointer->ptr = pointer; // ptr contains the address of pointer
i++;
}
system("pause");
}
Let us assume after ... | For starters, there will be no memory allocated for any ptr with the code you have.
int i = 0;
while( i >= 3)
This will not enter the while loop at all.
However, if you are looking to access the ptr contained inside the struct then you can try this. I am not sure what you are trying to achieve by assigning the ptr wi... |
7,266,097 | 7,274,649 | Are there any efforts to create a package manager for C++? | One of my biggest frustrations with my favorite language is the effort it takes to get different libraries working for together under one unified development environment. My biggest wish is to just be able to tell my IDE, or whatever, that I need a certain library, and it takes care of downloading it, compiling it(if ... | If you are using MinGW, there is already a package manager similar to apt-get / aptitude which does what you want: mingw-get
It behaves similar to Debian's apt-get/aptitude. Among the packages that are already included you can find expat, libxml2, zlib, pthread etc.
Obviously, you will need a copy of MinGW to start wor... |
7,266,202 | 7,266,639 | using to_iso_extended_string with boost date | I am trying to convert d2 to a string of the form '2011-08-02' so I can pass this to my sql statement. According to the boost site, to_iso_extended_string should return that format, but I get the following instead: '2011-Aug-02'.
date today(day_clock::local_day());
date_duration dd(30);
date d2=today-dd;
std::string to... | I have just tested this and it prints 2011-08-02 for me:
#include <iostream>
#include <string>
#include <boost/date_time.hpp>
namespace bg = boost::gregorian;
int
main ()
{
bg::date today (bg::day_clock::local_day());
bg::date_duration dd(30);
bg::date d2 = today - dd;
std::string str(to_iso_extended_... |
7,266,207 | 7,266,223 | Temporary not getting destructed at the end of the statement | Is this behaviour guaranteed all the time ? The code below creates a char* pointer using temporary unique_ptr. I thought the unique_ptr should get destructed at the end of the statement. To my surprise, the char* still points to valid memory.
void Fill(char* str, long len)
{
for(int i = 0; i < len; ++i)
st... | That is invoking undefined behavior. Undefined behavior means anything can happen, including having it appear to work. The temporary unique_ptr is in fact being destructed, and as a result deallocates the 100-element char array. You're reading and writing into a memory location that is not allocated to you anymore.
It... |
7,266,236 | 7,266,302 | How in the third call temp2->next is able to access the address of the second node when the address was destroyed because of local scope? | struct node {
char name[20];
int age;
int height;
node* next; // Pointer to the next node
};
node* startPTR = NULL; // global
void addNode_AT_END() {
node *temp1;
node *temp2;
temp1 = new node;
cout << "Enter the name : ";
cin >> temp1->name;
cout << endl << "Enter the age ... | It's only the pointer variables temp1 and temp2 that are of local scope. The actual linked-list nodes (of type struct node) are allocated on the heap via the call to new. Heap allocated data persists until it's free'd via a call to delete.
This means that the line temp2->next = temp1 is storing the address of the new n... |
7,266,762 | 7,266,798 | Accessing direct memory addresses and obtaining the values in C++ | I was wondering if it was possible to access a direct block of memory using C/C++ and grab the value. For example:
int i = 15;
int *p = &i;
cout << &i;
If I took the printed value here, that would give me the address of the variable i, which contains the value 15. I will just say it printed out 0x0ff9c1 for this examp... | The two processes have separate address spaces. One process cannot access another processses memory unless it is explicily shared memory.
|
7,266,915 | 7,267,210 | Why do these two constructors together not produce an ambiguity error? | Consider the following:
class A
{
private:
A() {}
public:
A(int x = 0) {}
};
int main()
{
A a(1);
return 0;
}
I have two constructors, one is a default and the other one is converting constructor with a default argument. When I try to compile the code, I expected an ambiguity error, but the compiler ... | Your code compiles because there is no ambiguity. You created a class with two constructors, one which always takes 0 arguments, and one which always takes one argument, an int. You then unambiguously called the constructor taking an int value. That this int has a default value does not matter, it is still a complet... |
7,267,061 | 7,267,137 | Alternatives to Singletons | This is related to: What is so bad about Singletons
Can you give me some examples where Singletons can be avoided using other techniques?
I need to use this in C++ so you can give examples with C++ specific techniques.
To be more clear: How you would implement a file manager, resource manager, log manager, etc without... | Simple: create a single instance of your file manager (or whatever) class, and then pass it around inside your application as necessary. Much will depend on your application structure, but typically you have some sort of controller object that creates the other important objects in the application. That might be the ob... |
7,267,090 | 7,267,139 | Why am I getting an exception whenever I use the CFileDialog? | Whenever I run my application under the debugger, I get the following exception when using CFileDialog to browse for a file to open
First-chance exception at 0x769db9bc in MyApp.exe: 0x000006BA: The RPC server is unavailable.
First-chance exception at 0x74e8cd99 in MyApp.exe: 0xC0020043: An internal error occurred in R... | First-chance exception messages can be safely ignored. In this case, this is part of Windows API internal implementation. Exceptions are thrown and caught somewhere. You need to turn off only first chance exception break in the debugger.
|
7,267,115 | 7,267,181 | error: no matching function for call to | #include <iostream>
using namespace std;
template <typename x> x functionA (x, x);
int main ()
{
functionA <double, double, double> (1, 1) << "\n";
}
template <typename x> x functionA (x arg1, x arg2)
{
return arg1 + arg2;
}
This code results in:
error: no matching function for call to ‘functionA(int, int)’... | The function template has one template parameter only, and you're passing 3 template arguments to it:
functionA <double, double, double> (1, 1) << "\n";
Why 3 template arguments?
Just write:
functionA <double> (1, 1);
Or you can simply let the compiler deduce the template argument, as:
functionA(1.0, 1.0); //templat... |
7,267,199 | 7,267,362 | c++ what does "iter = ++iter" do? is it valid? | I have a question on c++ std iterators.
suppose iter is std::set<SomeType>::iterator type.
Is:
iter = ++iter
the same as:
++iter
or are they different?
edit:
I found a code std::set<UserDefinedClass*>::iterator
being used that way. (pointer)
I wonder if that can cause the program I'm debugging malfunction.
I... | There's no definitive answer to this question. The answer depends on the nature of std::set<SomeType>::iterator type. If it is a user-defined type (i.e. a class with overloaded operators), then the behavior of iter = ++iter is defined ans is indeed equivalent to a mere ++iter. However, if std::set<SomeType>::iterator i... |
7,267,295 | 7,267,734 | How can I copy a file from one directory to another in c/c++ | I am looking for a simple example on how to copy a file from one directory to another in C. The program should only use cross platform functions that are native to C.
| Here is a simple untested C program that does what you need:
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argn, char * argv[]) {
int src_fd, dst_fd, n, err;
unsigned char buffer[4096];
char * src_path, dst_path;
// Assume that the program takes two argume... |
7,267,407 | 7,267,484 | Reference of pointer and left shift operator | I have redefined the << operator and I want it to take a reference of pointer.
class foo
{
foo();
virtual ~foo();
void operator << (BaseService*& iRight);
}
Somewhere in the code, having a foo instance, and a service which is a specialization of the BaseService class I do :
Service* service_pointer = new ... | The first version does not work because you can't pass in a reference to a pointer to a subtype and rightly so: What if the implementation of operator<< made the pointer point to an instance MyService (which is a subclass of BaseService, but not of Service)? Clearly it would be illegal for a Service* to point to a MySe... |
7,267,434 | 7,267,594 | C++: How to create small speed tests for templated classes? | First I'll show what I camed up with and I want to know how if you think that my solution is risky, bad and incompedent. We have a normal std map. We want to make it safe for multythreaded read/write operations. And test its speed. With boost we have 2 options use - mutable boost::mutex or boost::shared_mutex. So this ... | If you are trying to measure performance of the two different implementations, you should probably be using a test that mimics the expected behavior of the class under stress. That probably involves quite a lot more operations than the put, contains, get; get; get;, remove, and probably run for a while in a loop. Also ... |
7,267,501 | 7,267,653 | error: php.h no such file or directory | I am working with the following tutorial: http://abhinavsingh.com/blog/2008/12/php-extensions-how-and-why/
I did create in a folder the php_sample.h file. I have an error: php.h no such file or directory. I've installed php and apache using apt-get install. SHould i import in my file php.h ? I also don't know where to ... | you need php-dev package. php is just binary package while php-dev contains source files.
|
7,267,562 | 7,267,768 | Virtual inheritance (diamond) - Why do I need to upcast to Base class from the most Derived class | consider the following :
#include <iostream>
#include <string>
using namespace std;
class A {
public:
A(const char* sName) //conversion constructor
: _sName(sName) {cout<<"(1)"<<endl;} ;
A(const A& s) {cout<<"(2)"<<endl;} //copy constructor
virtual ~A() {cout<<"(3)"<<endl;} //destructor
void ... | Constructor of virtual base is called before nonvirtual ansestors ctor's. In your example B1 ctor can not invoke the virtual base constructor for C as B1 ctor itself will be called later.
|
7,267,838 | 7,268,095 | Division by zero does not throw SIGFPE | I have a small program performing floating-point division by zero, so I expect SIGFPE.
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
void signal_handler (int signo) {
if(signo == SIGFPE) {
std::cout << "Caught FPE\n";
}
}
int main (void) {
signal... | For floating point numbers you can change this behavior by setting up FPU control word. Take a look here
|
7,267,847 | 7,267,888 | Possible ways to identify Linux friendly code | I have a program that accesses a device through the serial port and reads the flash memory and displays it in command prompt. It saves the readings to ms access for logging.
I want to use this program on Linux so I figured that if I remove the MS access logging code it would port as serial ports and command prompt sho... | Just try compiling the code on Linux and try to look in to the compile errors, Whatever doesn't belong to Linux won't compile and you need to port/write similar functionality for Linux port.
Or am I missing something here? This looks fairly straightforward.
|
7,268,089 | 7,268,157 | how is x&&y||z evaluated? | Given
int x=1,y=2,z;
Could you explain why the result for:
x && y || z
is 1?
x && y = 1
x && y || z = 1
| x && y || z
is equivalent to
(x && y) || z
if x=1 and y=2
then x&&y is 1 && 2 which is true && true which is true.
true || z
is always true. z isn't even evaluated
|
7,268,285 | 7,268,464 | Using same operator with different parameters | I'm considering a "map of maps" type, and wonder if it would be considered bad practice to have two operator[]s, with different parameters having different meaning. Suppose the "outer" map is indexed by OuterKeyType and the inner maps by InnerKeyType, and we have an object of the "map of maps" m. Then the behaviour wou... | The first thing is that it is a really bad idea in general to hide different behaviors under the same function name just by the operands that are being passed. It makes it hard to determine what logic will be triggered when you encounter obj[value], as it will have completely different behavior depending on what value ... |
7,268,496 | 7,268,781 | boost.python expose function that returns vector<MyClass> | I'm writing an extension module for Python in C++ and I am using boost.python. I want to expose a function that returns a vector<MyClass>. I'm not exactly sure how to do this and how it will interact with Python WRT memory management.
My first thought was to wrap MyClass in shared_ptr, thus the function would return ve... | If you use vector<MyClass> those instances in the vector are obviously (kind of, since the vector internally uses dynamically allocated memory) stack allocated. It would be different to vector<MyClass*> which is essentially a vector of dynamically allocated MyClass instances. In this case, a vector<shared_ptr<MyClass> ... |
7,268,800 | 7,275,542 | SSE micro-optimization instruction order | I have noticed that sometimes MSVC 2010 doesn't reorder SSE instructions at all. I thought I didn't have to care about instruction order inside my loop since the compiler handles that best, which doesn't seem to be the case.
How should I think about this? What determines the best instruction order? I know some instruct... | I agree with everyone that testing and tweaking is the best approach. But there are some tricks to help it.
First of all, MSVC does re-order SSE instruction. Your example is probably too simple or already optimal.
Generally speaking, if you have enough registers to do so, full interleaving tends to give the best result... |
7,268,901 | 7,270,713 | Template specialization by another template (of same class) | I'm writing an array class. This array class can contain again arrays as members. When implementing a printing function, I need specializations.
26:template <class T> class array : public vector<T>{
public:
...
string* printToString();
...
};
...
template <class T> string* array<T>::printToStr... | As an alternative to David's solution, you can unconditionally forward the call to a set of overloaded functions:
template <class T> class array;
namespace details {
template <class T> std::string array_print(array<T> const&);
std::string array_print(array<double> const&); // Regular function
template <class T> ... |
7,269,099 | 7,273,599 | May I treat a 2D array as a contiguous 1D array? | Consider the following code:
int a[25][80];
a[0][1234] = 56;
int* p = &a[0][0];
p[1234] = 56;
Does the second line invoke undefined behavior? How about the fourth line?
| It's up to interpretation. While the contiguity requirements of arrays don't leave much to the imagination in terms of how to layout a multidimensional arrays (this has been pointed out before), notice that when you're doing p[1234] you're indexing the 1234th element of the zeroth row of only 80 columns. Some interpret... |
7,269,166 | 7,269,301 | Abstract class with pure virtual method - why is it possible to do "Abstract * abs3;"? | Consider the following :
class Abstract
{
public:
virtual void func() = 0;
};
int main() {
Abstract abs1; // doesn't compile
Abstract * abs2 = new Abstract(); // doesn't compile
Abstract * abs3; // compiles
return 0;
}
Please notice that I didn't implement func() , so why is it possible to do ... | abs3 is a pointer to the class. It can be initialized to any concrete subclass of Abstract, or to NULL, safely. The compiler has to allow it because while you can't create abstract classes, you have to be able to create pointers to them. See below for an example
class Concrete: public Abstract
{
public:
virtual ... |
7,269,369 | 7,269,516 | Can wrapping a type in a struct cause additional padding? |
Possible Duplicate:
Size of struct with a single element
Given any type A and the following struct:
struct S
{
A a;
};
Are there any cases where sizeof(S) is greater than sizeof(A)?
For example, can sizeof(std::array<T, n>) be greater than sizeof(T[n])?
| While the struct can be padded, on all systems I know, the compiler will pad so that the alignment of the structure is the same as the largest alignment of its members. It does this so that an array of the structure will always be correctly aligned.
So:
struct S
{
char a;
} // Size 1, no padding
struct S2
{
... |
7,270,494 | 7,270,556 | Why would a C++ compiler only eliminate useless writes if there's no code after those writes? | I'm inspecting Visual C++ 10 optimization capabilities and found a rather curious thing. All code herein is compiled with /O2.
In the following code:
int _tmain(int argc, _TCHAR* argv[])
{
char buffer[1024] = {};
MessageBoxA( 0, buffer, buffer, 0 );
memset( buffer, 0, sizeof( buffer ) );
return 0;
}
th... | The compiler probably can't tell that MessageBoxA doesn't create an alias to buffer that's then used by Sleep later. Thus it fails the "as-if" check.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.