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,705,139 | 3,706,904 | Argument forwarding for no argument cases | I have a class like this:
template<class T> class A : public T {
// this is done to wrap the base class version of a virtual function
virtual void F(int i) {
if(i < 0) T::F(-i);
else T::F(i);
}
//...
that needs to be constructible for any set of args the base class can be constructed with:
template <typename T... |
fails if T has no default constructor
even if A() isn't called.
class X
{
public:
X(int) {}
};
template <class T>
class A: public T
{
public:
A(): T() {}
template <class U>
A(const U& u): T(u) {}
};
int main()
{
A<X> a(1);
//A<X> b;
}
This appears to compile fine with several compilers. I... |
3,705,306 | 3,705,322 | Call c++ member function with each element in a list? | I have a list of Thing and a Controller that I want to notify() with each of the things. The code below works:
#include <algorithm>
#include <iostream>
#include <tr1/functional>
#include <list>
using namespace std;
class Thing { public: int x; };
class Controller
{
public:
void notify(Thing& t) { cerr << t.x << e... | You can accomplish this using bind, which is originally from Boost but is included in TR1 and C++0x:
using std::tr1::placeholders::_1;
std::for_each(things.begin(), things.end(),
std::tr1::bind(&Controller::notify, c, _1));
|
3,705,380 | 3,705,396 | Good software for software planning? | Is there software that can help create flow charts, class diagrams etc to help software development planning.
Thanks
| You can create all kinds of charts and diagrams with something like Microsoft Visio or the open-source Dia.
If you want to auto-generate things like this, take a look at using a UML-based tool. A list of some UML tools is available here.
|
3,705,563 | 3,732,505 | Code Blocks, MinGW, Boost, and static linking issues | I am using Code Blocks with MinGW and am trying to get a simple program to compile with static linking. I have built the Boost libraries using these directions. Everything worked out fine and I was able to successfully compile this simple program (it compiles, I know it doesn't work because it exits before the messag... | It's from trying to link statically when the headers are configured for a dynamic link. I explain this for libssh in this question. Poking around in boost/thread/detail/config.hpp makes me think you should #define BOOST_THREAD_USE_LIB, or use the -D flag to do the same.
|
3,705,611 | 3,705,629 | Why doesn't Xcode + Instrument Leaks detect this leak in simple C++ program | I have the following in a simple C++ console project in Xcode.
When I run this with instrument Leaks, Xcode does not flag any memory leaks
even thought there is a glaring one. What is going on ? Any help?
#include <iostream>
int main (int argc, char * const argv[]) {
// insert code here...
int *x = new int[20... | There's no leak in your code. For a leak to occur, you have to lose the reference you have to allocated memory. In your case, you do nothing more with the allocated memory, but you still keep a reference to it. Therefore, Leaks thinks you could potentially free it later at some point, and doesn't consider it a leak. (A... |
3,705,740 | 3,705,774 | C++ - LNK2019 error unresolved external symbol [template class's constructor and destructor] referenced in function _main | [[UPDATE]] -> If I #include "Queue.cpp" in my program.cpp, it works just fine. This shouldn't be necessary, right?
Hey all -- I'm using Visual Studio 2010 and having trouble linking a quick-and-dirty Queue implementation. I started with an empty Win32 Console Application, and all files are present in the project. For v... | Why don't you follow the "Inclusion Model"? I'd recommend you follow that model.
The compiler needs to have access to the entire template definition (not just the signature) in order to generate code for each instantiation of the template, so you need to move the definitions of the functions to your header.
Note: In ge... |
3,705,960 | 3,706,002 | Run the same C++ Program from different Binary Names | Okay, for a homework assignment my professor wants us to write a program in C++ that converts from miles to km. I did all that, the program runs. However, he has this special way of calling the program:
The program's usage options are based
on the NAME of the BINARY FILE. If
the program name is 'km2miles', the
... | You can:
specify a name when you build it, and build it twice
on Windows: copy convert miles2kms; copy convert kms2miles
on UNIX/Linux: cp convert miles2kms; cp convert kms2miles
on UNIX/Linx (better): make a link or symbolic link: ln -s convert miles2kms; ln -s convert kms2miles.
Inside your program, you should be d... |
3,706,031 | 3,714,827 | Number of Items in a Column inside a grid | How do you find number of items in a column inside a grid?
I have a grid (listview control to be specific), and have some items.
Some times a given row might not be full. ANd can have values in fewer than maximum columns. I need to find Number of items in a given Column.
If the grid is like
1 2 3
4 5 6
7 ... | Assuming 0-based indexes:
def itemsInColumn(itemCount, columnCount, inputColumn):
lastItemColumn = (itemCount - 1) % columnCount
if inputColumn <= lastItemColumn:
return (itemCount + columnCount - 1) / columnCount
else:
return itemCount / columnCount
It depends on the total number of items (itemCount) an... |
3,706,086 | 3,706,095 | Using sprintf will change the specified variable | I have a code,
char* bin2hexchar( const unsigned char& ibin, char* pbcd )
{
sprintf( pbcd, "%02X", ibin );
return pbcd;
}
The problem is, the value of ibin variable will change to zero value.
Please advice.
Thanks
| If your ibin is changing to a zero value in the caller to this function, the most likely explanation is buffer overflow.
I suspect it's probably because the buffer you're passing in as the second argument is defined thus:
char buff[2];
and ibin is adjacent to it on the stack.
The %02X format string requires three byte... |
3,706,154 | 3,706,297 | A design issue with a tree of information in C++ | Sorry in advance for the lengthy explanation!
I have a C++ application that uses a hash_map to store a tree of information that was parsed from a text file. The values in the map are either a child hash_map or a string. These values were parsed from a text file and then stored into the map.
I wanted to avoid having to ... | Use boost::variant (which is equivalent to a C++ union for user-defined types), C++ union (applicable in this case as you're working with only pointers) or boost::any (which can store any type) to store a pointer to either hash_map or string.
|
3,706,285 | 3,706,458 | Why don't my widgets get displayed? | I am trying to create layout like this
In the QT i created widgets and put in the main widget, the problem is not visible. none of the widget's are not shown. please help me to fix this issue
Complete Source Code
sandbox.ifuturemec.com/test.zip
Source code
mainWindow.cpp
#include "mainwindow.h"
#include <QtGui>
#incl... | Actually, your widgets do show ! But they are empty and have nothing to show !
Regarding the background color you are setting : the background-color property is not showing, because this property is not supported by QWidget.
Have a look at the documentation regarding this : List of stylable widgets.
More specifically :... |
3,706,379 | 3,706,598 | What is a good naming convention for vars, methods, etc in C++? | I come from a the Objective-C and Cocoa world where there are lots of conventions and many people will say it makes your code beautiful!
Now programming in C++ I cannot find a good document like this one for C++.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.ht... | Do whatever you want as long as its minimal, consistent, and doesn't break any rules.
Personally, I find the Boost style easiest; it matches the standard library (giving a uniform look to code) and is simple. I personally tack on m and p prefixes to members and parameters, respectively, giving:
#ifndef NAMESPACE_NAMES_... |
3,706,917 | 3,707,054 | How to prevent a Linux program from running more than once? | What is the best way to prevent a Linux program/daemon from being executed more than once at a given time?
| The most common way is to create a PID file: define a location where the file will go (inside /var/run is common). On successful startup, you'll write your PID to this file. When deciding whether to start up, read the file and check to make sure that the referenced process doesn't exist (or if it does, that it's not ... |
3,706,947 | 3,706,972 | How do I convert this code to c++? | I have this code:
string get_md5sum(unsigned char* md) {
char buf[MD5_DIGEST_LENGTH + MD5_DIGEST_LENGTH];
char *bptr;
bptr = buf;
for(int i = 0; i < MD5_DIGEST_LENGTH; i++) {
bptr += sprintf(bptr, "%02x", md[i]);
}
bptr += '\0';
string x(buf);
... | sprintf returns number of bytes written. So this one writes to bptr two bytes (value of md[i] converted to %02x -> which means hex, padded on 2 chars with zeroes from left), and increases bptr by number of bytes written, so it points on string's (buf) end.
I don't get the bptr += '\0'; line, IMO it should be *bptr = '\... |
3,706,997 | 3,707,025 | COM - what does _pAtlModule->Lock() lock exactly? | I'm working my way through learning writing a COM control. I've got an example project, and it uses the lines
_pAtlModule->Lock()
_pAtlModule->Unlock()
in the OnCreate() handler and the OnDestroy() handler for the COM control respectively.
I realise that the _pAtlModule is an instance of the CAtlModule - the "applica... | On the outsude, it doesn't actually appear to do anything substantial!
MSDN says "It increases the Lock count and returns the updated value; This may be useful for debugging and tracing".
http://msdn.microsoft.com/en-US/library/9syc2105%28v=VS.80%29.aspx
I think this is misleading however, the behavior is intended to ... |
3,707,096 | 3,707,163 | Spiral rule and 'declaration follows usage' for parsing C and C++ declarations | This question follows this other question about C declarations. Reading the answer to this question, I read about the spiral rule and I also understood what "declaration follows usage" means.
Ok so far. But then I read this declaration:
char *(*(*a[N])())();
and I was wondering how to parse it with the "declaration f... | You just have to build it up in steps.
char *X(); // X =~ (*(*a[N])())
Function returning char*
char *(*Y())(); // Y =~ (*a[N])
Function returning pointer to function returning char*.
In a declaration, just as in an expression (declaration follow usage), postfix [] has a higher precedence that unary * so *a[N] is e... |
3,707,125 | 3,715,632 | Flexible application configuration in C++ | I am developing a C++ application used to simulate a real world scenario. Based on this simulation our team is going to develop, test and evaluate different algorithms working within such a real world scenrio.
We need the possibility to define several scenarios (they might differ in a few parameters, but a future scena... | I found this website with a nice template supporting factory which I think will be used in my code.
|
3,707,133 | 3,709,916 | How to use ZwQueryInformationProcess to get ProcessImageFileName in a kernel driver? | I'm writing a simple kernel driver for my application (think of a very simple anti-malware application.)
I've hooked ZwOpenFile() and used PsGetCurrentProcess() to get a handle to the caller process.
It returns a PEPROCESS structure:
PEPROCESS proc = PsGetCurrentProcess();
I'm using ZwQueryInformationProcess() to get ... | The MSDN docs for this API indicate that
When the ProcessInformationClass
parameter is ProcessImageFileName, the
buffer pointed to by the
ProcessInformation parameter should be
large enough to hold a UNICODE_STRING
structure as well as the string
itself. The string stored in the
Buffer member is the nam... |
3,707,138 | 3,707,571 | why ostringstream could not work well in multithreading environment | Maybe something is weird. When I use STL ostringstream class in my multithreading environment I found that the execution time of each thread increased linearly as the thread number increased. I don't know why this happened. I try to check the ostringstream source code but could not find any synchronization code. Are th... | It seems to be a known problem. Here is a solution for MSVC: linking statically. Perhaps this will also work on linux.
ALternatively (suggested for Sun Studio here), make the streams thread local (instead of process local) to prevent them from being locked by each thread as the other accesses them.
|
3,707,160 | 3,707,167 | C++ Array of Objects | I have an array in a class that should hold some instances of other objects. The header file looks like this:
class Document {
private:
long arraysize;
long count;
Row* rows;
public:
Document();
~Document();
}
Then in the constructor I initialize the array like this:
this->rows = new Row[arraysize]... | If arraySize contains a reasonable value at that point you actually get an array. I guess you trust your debugger and the debugger only shows the 0th element (that's how debuggers treat pointers), so you think there's only one object behind that pointer.
|
3,707,278 | 3,707,534 | How to implement std::set or std::hash_set to filter the duplicated item in an array list? | Given the below scenario, I'm having a list of item which might be having some duplicated item.
I would like to filter the item, to print the only unique item.
Instead of duplicating a list which remove the duplicated item, I tried to insert them into std::set and std::hash_set. Nevertheless, I found no useful example... | Removing duplicates is easy, assuming you can modify the sequence.
First you will need less-than and equality functors:
struct less_SWVERSIONSTRUCT
{
bool operator () (SWVERSIONSTRUCT const & a, SWVERSIONSTRUCT const & b) const
{
// Replace this with the appropriate less-than relation for the structure.
ret... |
3,707,311 | 3,707,368 | Multiple Partial specialization and full specialization required <> after type definition | I'm using an C++ "event" class that allowed one or two arguments in the to be called delegates.
Lately I've added support for delegates that don't require arguments, however when I specialze the class to use no template arguments I'm still required to add <> afther the class definition.
Example usage with one/two argum... | If you want to call a function foo with no arguments you have to write foo() not just foo. That is exactly the same for template types. event is not a type, it is a "function" that takes types and return a type.
If you really want to avoid writing the brackets, you can still do something like:
typedef event<> event_;... |
3,707,406 | 3,722,662 | I want to allow an xml file concurrent read accesses | I want to allow an xml document, that contains some configuration items, concurrent read-accesses (no write access) from several machines on a domain.
Could a simple DOMDocument30 be just what I need.
Or do you think FreeThreadedDOMDocument xml document template should be sufficient.
Or do you think of other xml docum... | FreeThreadedDOMDocument is thread-safe in terms of reading. You can use this COM component in your project.
|
3,707,442 | 3,707,533 | What is the difference between -0 and 0? | In C++, for example fmod(-2,2) returns -0. The expression -0 == 0 is true, but the bits are different. What is the purpose of having something like -0 which should be 0 but is represented differently? Is -0 used exactly the same way as 0 in any computations?
| No, +0 and -0 are not used in the same way in every computation. For example:
3·(+0) = +0
+0/-3 = -0
I suggest you to read What Every Computer Scientist Should Know About Floating-point arithmetic by David Goldberg, that sheds a light on why +0 and -0 are needed in floating point arithmetic and in which way they diffe... |
3,707,709 | 3,707,777 | Cross-platform GUI toolkit in C or C++? | I'm looking to write some simple GUI applications in C or C++, and am stuck for choice between the cross-platform toolkits. Keep in mind that I am developing in Ubuntu, preferably without an IDE, and preferably with good cross-platform support.
What are the pros and cons of some of these toolkits? Which have you had th... | I have experience with Qt and wxWidgets. Both are OK for simple GUI applications, but Qt looks more professional. I like that it keeps GUI definition code in separate files (like in .NET WinForms designer), and it is not mixed with our own code. Qt Creator is good IDE which may be used also for developing non-Qt C/C++ ... |
3,707,927 | 3,708,034 | Package accessibility for function and/or class | In Java they have package access specifier which enables the function to be used only by classes from this same "package" (namespace) and I see good things about it. Especially when design of models are in play. Do you think that something like this could be useful in C++?
Thanks.
| Yes, this can be accomplished. You may restrict visibility by public, protected, private keywords, as well as source visibility.
Declared visibility is commonly understood.
Source visibility (if you're coming from Java) is a bit different.
Java: you have one file for an object interface/implementation.
Cpp: you have on... |
3,708,141 | 3,708,317 | c++ array class problems | Alright, so without going into detail on why I'm writing this class, here it is.
template<class aType>
class nArray
{
public:
aType& operator[](int i)
{
return Array[i];
}
nArray()
{
aType * Array = new aType[0];
_Size = 0;
_MaxSize = 0;
_Count = 0;
}
nArray(int Count)
... | int Resize(int newSize)
{
.
.
aType * Array = new aType[newSize*2];
At this point, instead of updating the member variable as you intended, you've actually created a local variable called Array whose value is discarded when you exit from Resize(). Change the line to
Array = new aType[newSize*2];... |
3,708,160 | 3,708,328 | What is the effect of InterlockedIncrement argument declared as volatile | InterlockedIncrement and other Interlocked operations declare their arguments as volatile. Why? What is the intention and effect of this?
| The probable effect is very minimal. The most likely intent is to allow users to pass volatile-qualified variables to these functions without the need for a typecast.
|
3,708,237 | 3,709,093 | C++ MFC: How to open immediately a secondary dialog after the first modal dialog was created | how can I open a secondary modal dialog in C++ MFC from a dialog without pressing any button?
(If I create a dialog in OnInitDialog(), the first dialog won't appear.)
| Just call ShowWindow(SW_SHOW); in your OnInitDialog just before display the secondary dialog.
|
3,708,383 | 3,708,401 | In C++, are changes to pointers passed to a function reflected in the calling function? | If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?
For example, if I need to delete the first node in a linked list:
void f2( Node *p)
{
Node *tmp = p;
p = p -> next;
delete tmp;
}
Will the changes made to P ... |
If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?
No. Since C and C++ implement pass-by-value, the value of the pointer is copied when it’s passed to the function. Only that local copy is modified, and the value is not... |
3,708,390 | 3,709,798 | Installing OpenCV on OSX 10.6 using MacPorts | I tried installing OpenCV following the instructions for a MacPorts install on http://opencv.willowgarage.com/wiki/Mac_OS_X_OpenCV_Port, typing
sudo port install opencv
in the terminal.
The install/compilation seemed to go fine, and the files are in /opt/local subdirectories as they should be. As a first test, I then ... | MacPorts installs C/C++ headers in /opt/local/include directory which is not the system default. It means that you have to explicitly tell GCC where to look for headers you are using. You can do that by specifying "-isystem" or "-I" command line options:
-isystem dir
Search dir for header files, after all... |
3,708,466 | 3,709,200 | Does SQLite3 change databases even if every statement is "SELECT" | we try to deploy our software on Windows 7, and there are several sqlite3 db files around. But, these are all read-only and we execute only "SELECT" statements. However, we have observed that Windows 7 also make virtualization on these files, which means file structure or content is changed. What do you think of it? Wh... | Do these databases exist in your Program Files folder? If so, you should take a look at e.g. this article on MSDN. Data files shouldn't go in the Program Files folder but in Program Data. Otherwise, if you really positively absolutely have to put the databases in the Program Files folder, make sure you pass SQLite th... |
3,708,469 | 3,709,090 | C++ structs Interdependency | Hello i have structures declared in the same Header file that need eachother.
struct A; // ignored by the compiler
struct B{
A _iNeedA; //Compiler error Here
};
struct A {
B _iNeedB;
};
this work normally
class A;
class B{
A _iNeedA;
};
class A {
B _iNeedB;
};
// everything is good
Thank you very muc... | I answer my own question.
the fact is what im doing is not exactly what i posted but i thougt it was the same thing, actually i'm using operators that take arguments. Thoses operators body must be defined after my structs declarations (outside the struct),
because struct B don't know yet struct A members...
I said it w... |
3,708,593 | 3,708,861 | Alternative to template declaration of typedef | I'm trying to accomplish
namespace NTL
{
typedef std::valarray vector;
}
through standard C++. I know it's not allowed, but I need a quick and easy way (without reimplementing all functions, operators, overloads, etc.) to get a template typedef.
I am now doing a template class Vector which has a valarray as data m... | In C++0x that will be really simple, but for the time being you can approach the problem in two ways, through a metafunction or by abusing inheritance.
namespace NTL {
// metafunction
template <typename T>
struct vector_1 {
typedef std::valarray<T> type;
};
// inheritance abuse:
template <typen... |
3,708,599 | 3,709,989 | Boost xpressive ! operator not working | I just started using Boost::xpressive and find it an excellent library... I went through the documentation and tried to use the ! operator (zero or one) but it doesn't compile (VS2008).
I want to match a sip address which may or may not start with "sip:"
#include <iostream>
#include <boost/xpressive/xpressive.hpp>
usi... | You just encountered a bug that plagues most of the DSEL.
The issue is that you want a specific operator to be called, the one actually defined in your specific languages. However this operator already exist in C++, and therefore the normal rules of Lookup and Overload resolution apply.
The selection of the right opera... |
3,708,626 | 3,709,123 | VS2008(+?) compiler bug with templated functions and 'using namespace' | I've found this odd case of some code (below) doesn't compile under Visual Studio 2008 and produces an "error C2872: 'Ambiguity' : ambiguous symbol" on line 12.
Removing the using namespace RequiredNamespace on the last line fixes the error, but I'd expect that putting using namespace at the end of a file should have ... | I believe it's a bug, per 7.3.4 para 1 of the C++03 standard:
A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive.
So your end-of-file using declaration should have no effect.
|
3,708,706 | 3,708,718 | How to determine the Boost version on a system? | Is there a quick way to determine the version of the Boost C++ libraries on a system?
| Boost Informational Macros. You need: BOOST_VERSION
|
3,708,842 | 3,708,898 | Does Boost.Serialization serialize differently on different platforms? | I use Boost.Serialization to serialize a std::map. The code looks like this
void Dictionary::serialize(std::string & buffer)
{
try {
std::stringstream ss;
boost::archive::binary_oarchive archive(ss);
archive << dict_;
buffer = ss.str();
} catch (const std::exception & ex) {
throw DictionaryExce... | try using a text_iarchive and text_oarchive instead of binary archives. From the documentation
In this tutorial, we have used a
particular archive class -
text_oarchive for saving and
text_iarchive for loading. text
archives render data as text and are
portable across platforms. In addition
to text archive... |
3,709,031 | 3,709,052 | map<string, string> how to insert data in this map? | I need to store strings in key value format. So am using Map like below.
#include<map>
using namespace std;
int main()
{
map<string, string> m;
string s1 = "1";
string v1 = "A";
m.insert(pair<string, string>(s1, v1)); //Error
}
Am getting below error at insert line
error C2784: 'bool std::operator <(... | I think you miss a #include <string> somewhere.
|
3,709,207 | 3,709,257 | C++ semantics of `static const` vs `const` | In C++ specifically, what are the semantic differences between for example:
static const int x = 0 ;
and
const int x = 0 ;
for both static as a linkage and a storage class specifier (i.e. inside and outside a function).
| At file scope, no difference in C++. const makes internal linkage the default, and all global variables have static lifetime. But the first variant has the same behavior in C, so that may be a good reason to use it.
Within a function, the second version can be computed from parameters. In C or C++ it doesn't have to ... |
3,709,273 | 3,717,449 | Adding images using opencv | I'm trying to add several images using opencv. I think that my source code should be correct and it compiles without any problems. But when I start the program an error occurs in the for-loop. The problem is that I don't understand why this is happening.
#include <iostream>
#include <sys/types.h>
#include <... | I solved the problem. I had some other files in the working directory, that weren't *.png files and then the loop didn't work. Absolutely clear that the program couldn't load the other files and work with them... I just don't understand, why the part of the program isn't working that should take care of this problem...... |
3,709,389 | 3,709,451 | Overloading << operator in C++ | I want to overload << operator in a Line class so I can print an object using cout like this:
cout << myLineObject << endl;
but this is not working:
class Line{
public:
float m;
float b;
string operator << (Line &line){return ("y = " + line.m + "x + " + line.b);};
};
I get:
Invalid operands of types 'cons... | operator<< has to be a non-member function, since the stream is the left-hand argument. In your case, since the data members are public, it can be implemented outside the class:
std::ostream& operator<<(std::ostream& stream, const Line& line)
{
return stream << "y = " << line.m << " x = " << line.b;
}
|
3,709,454 | 3,725,610 | Direct Show Capture filter "wrapper" | I need to write a DirectShow capture filter that wraps the "real"
video device (fitler) and deinterlaces the captured video. From the
interface perspective, this has to be a separate video device
available in enumerator and when choosen, it connects to a real video
device and inserts a transform filter (deinterlace... | To deinterlace without a wrapper, you can create a transform filter and give it a very high merit, that way it can be automatically added (injected) to graphs. See MatrixMixer which does something simular for audio.
If you really need a wrapper, create a second graph with the original video device and the transform fil... |
3,709,548 | 3,709,590 | changing const value in C | I find that in the following code snippet
const int i = 2;
const int* ptr1= &i;
int* ptr2 = (int*)ptr1;
*ptr2 =3;
i's value changes to 3. What I could like to know is why is this allowed. What are the situations in which this could become helpful?
| It's allowed because you have overruled the constness of ptr1 by casting it to a non-const pointer. This is why casts can be very dangerous.
Note that some compilers, such as GCC, will not allow you to cast away const status like this.
|
3,709,637 | 3,709,706 | COleDateTimeSpan: GetTotalDays vs GetDays | Both functions GetTotalDays and GetDays of COleDateTimeSpan class returns number of days contained in object:
GetTotalDays: http://msdn.microsoft.com/en-us/library/d22h87z4(v=VS.80).aspx
This date/time-span value expressed in days
GetDays: http://msdn.microsoft.com/en-us/library/ze8kz4yw(v=VS.80).aspx
The day portio... | They look the same apart from the fact that GetTotalDays returns double. If I had to guess, I'd say that originally this was intended to provide a means to express the fractional parts of a day as well as full days, and then someone at Microsoft decided this was not such a great idea. The API may therefore only exist... |
3,709,827 | 3,709,864 | issue with pointers and constructors | The following code doesn't work:
class String{
public:
char* str;
int* counter;
String(){
str = NULL;
counter = new int;
*counter = 1;
};
String(const char* str1){
String();
str = new char[strlen(str1)+1];
strcpy(str, str1);
};
};
I've changed... | "Doesn't work" is not a good description of the problem. But you apparently tried to invoke a constructor from another one. That's called constructor delegation and is not (yet) supported by C++.
BTW, a class like this should get a user-defined copy constructor, assignment operator and destructor.
|
3,709,874 | 3,709,884 | Is this piece of C++ considered okay in terms of memory management? | I am kind of getting bogged down by the concept of memory management (all my previous programming languages doesn't need me to manage the memory). I'm not sure if creating a variable will consume memory if I don't destroy it later.
#include <math.h>
#include <iostream>
using namespace std;
double sumInfiniteSeries(dou... | What memory management? You’re only using the stack here, no memory management needed.
Manual memory management comes into play when you fiddle with new and delete.
|
3,709,886 | 3,709,981 | sprintf, commas and dots in C(++) (and localization?) | I am working in a project using openframeworks and I've been having some problems lately when writing XMLs. I've traced down the problem to a sprintf:
It seems that under certain conditions an sprintf call may write commas instead of dots on float numbers (e.g. "2,56" instead of "2.56"). In my locale the floating numbe... | The decimal separator is controlled by the LC_NUMERIC locale variable. Set setlocale for details. Setting it to the "C" locale will give you a period. You can find out the characters and settings for the current locale by looking in the (read-only) struct returned by localeconv.
|
3,710,017 | 3,710,768 | How to write your own condition variable using atomic primitives | I need to write my own implementation of a condition variable much like pthread_cond_t.
I know I'll need to use the compiler provided primitives like __sync_val_compare_and_swap etc.
Does anyone know how I'd go about this please.
Thx
| Correct implementation of condition variables is HARD. Use one of the many libraries out there instead (e.g. boost, pthreads-win32, my just::thread library)
You need to:
Keep a list of waiting threads (this might be a "virtual" list rather than an actual data structure)
Ensure that when a thread waits you atomically u... |
3,710,176 | 3,713,248 | Changing CFrameWnd to CFrameWndEx in MFC causes unhandled exception - any ideas? | Still getting used to this MFC lark and I've hit a brick wall on this particular problem. I'm updating some legacy code to use some of the more refined controls available in the MFC Feature Pack.
Following the examples given online for updating an old MFC app, changing the base application class to CWinAppEx works fin... | The source code for the MFC framework is included as part of Visual Studio, so it should be installed on your computer. In general, when the framework triggers a debug assertion you should drop into the debugger and this will help you determine the exact cause of the problem.
Looking at the source code, I can see that ... |
3,710,180 | 3,714,214 | Compiling on Windows and Mac with Autotool | I have a problem trying to use autotools for a simple contrived project, the task is simple, use Objective-C on Mac OSX, and C++ on Windows (mingw) - with some C glue in the middle.
The project is structured like so (minus all the automatically generated files):
./aclocal.m4
./configure
./configure.ac
.... | I see that you're referring to greet.mm in the gist, but greet.m in the question. Automake does not appear to natively support Objective-C++ code. For Objective-C code, you need to have AC_PROG_OBJC in your configure.ac. If you really meant Objective-C++ code, you'll need to do this via a suffix rule.
|
3,710,202 | 3,710,449 | What's a good C++ code design for a one Template Object -> multiple Instance Objects architecture? | I have the following design request for a visual editing tool written in C++:
be able to define a template object (assign image, edit default rotation/scale, edit default property values)
be able to place instances of template object in view
be able to make changes to template object (eg different image, change rotati... | I don't see why this needs to be complicated. Unless there are additional constraints you're not letting us know about...
class RealItem;
class TemplateItem
{
//data members
public:
//set properties and such
RealItem MakeRealItem() const; //Generates a RealItem from this template.
};
class RealItem
{
... |
3,710,532 | 3,717,397 | Extending homework testing platform to include code analysis (C/C++) | I'm maintaining/developing a platform for homework testing. It's mostly automatic. What I need to add now is code analysis. I need to check the code for specific constructs.
For example:
Does the file main.cpp contain a
class named user with a const method
get_name()?
Is there some tool out there that would allo... | I have discovered dehydra tool from Mozilla. It seems to be mostly written for internal purposes, but it may just be exactly what I was looking for.
https://developer.mozilla.org/En/Dehydra/Using_Dehydra
Edit: Dehydra is great. It is missing some minor features like determining const methods, but otherwise great.
|
3,710,697 | 3,710,942 | How to generate random numbers in C++ using <random> header members? | I learned to program in C# and have started to learn C++. I'm using the Visual Studio 2010 IDE. I am trying to generate random numbers with the distribution classes available in <random>. For example I tried doing the following:
#include <random>
std::normal_distribution<double> *normal = new normal_distribution<do... | There is no variate_generator in C++0x, but std::bind works just as well. The following compiles and runs in GCC 4.5.2 and MSVC 2010 Express:
#include <random>
#include <functional>
#include <iostream>
int main()
{
std::normal_distribution<> normal(10.0, 3.0); // mean 10, sigma 3
std::random_device rd;
std:... |
3,710,749 | 3,710,789 | How can I ensure that a class has no virtual methods? | I have a class whose objects are used in shared memory. Therefore, I must be sure that they do not have virtual methods (which crash the program when called via vtable).
I would like to guard against anybody accidentally adding a virtual method in violation of this requirement. Ideally, the compiler would refuse to eve... | Well, I really think this doesn't make sense to enforce, but you could use boost type traits' is_polymorphic.
EDIT: Example:
#include <iostream>
#include <boost/type_traits.hpp>
struct Base
{
virtual void MyMethod() { std::cout << "My method called."; }
virtual ~Base() {}
};
class Derived : Base
{
virtu... |
3,710,796 | 3,744,589 | Simplest lua function that returns a vector of strings | I need a very simple c++ function that calls a lua function that returns an array of strings, and stores them as a c++ vector. The function can look something like this:
std::vector<string> call_lua_func(string lua_source_code);
(where lua source code contains a lua function that returns an array of strings).
Any idea... | Here is some source that may work for you. It may need some more polish and testing. It expects that the Lua chunk is returning the array of strings, but with slight modification could call a named function in the chunk. So, as-is, it works with "return {'a'}" as a parameter, but not "function a() return {'a'} end" as ... |
3,710,859 | 7,911,676 | IWebBrowser2 interfaces dependency graph | Is there interfaces dependency graph for IWebBrowser2 component?
I just want to make it clear what kind of dependencies exist between interfaces and who calls who?
| You can use dependencywalker http://www.dependencywalker.com/ on the file shdocvw.dll
|
3,711,097 | 3,711,202 | C++ STL list operator overloading for pairs (sorting according to first value, accessing with second value) | Hello I have some touble overloading operators for std::list.
I store pairs in a list, consisting in an int value and a position array :
typedef std::pair< int, std::vector<int,3> > pointPairType;
typedef std::list< pointPairType > pointListQueueType;
pointListQueueType pointsQueue;
// adding some points to the... | The first problem is that there is no such type std::vector<int, 3>. Assuming you meant to use 3-element arrays, std::array<int, 3> (or std::tr1::array or boost::array, depending on the compiler) is what you need, or just std::vector<int>.
Secondly, those int and std::vector<int, 3> are template parameters that tell th... |
3,711,267 | 3,711,446 | How to read c++ errors involving templates | I'm learning C++. I regularly get errors that look like this
/usr/lib/gcc/i686-pc-cygwin/4.3.4/include/c++/bits/basic_string.h:1458: instantiated from 'static _CharT* std::basic_string<_CharT, _Traits, _Alloc>::_S_construct_aux(_InIterator, _InIterator, const _Alloc&, std::__false_type) [with _InIterator = std::ist... | This is not the whole error, just a description of one instantiation.
Basically you care about:
1) which line in your code triggered the error (string s(begin,end);)
2) what error did it result in (e.g cannot convert 'const std::basic_string<char, std::char_traits<char>, std::allocator<char> >' to 'char' in assignment)... |
3,711,284 | 3,711,956 | vc++ installing libcurl | Hey, firstly thanks for reading this. I am a bit of a noobie c++ programmer with a great idea. For programming this I need to download some HTML off websites. I have chosen libCurl due to perform this task. The libcurl website is of little help to me. Most of the information on their website is outdated or deviates sli... | I can't post step-by-step instructions, but here are some general pointers about integrating 3rd party libs into your application with VC projects:
Add the curl include statement to one or more of your header files:
#include <curl/curl.h>. You can do this in any source files that need to access the curl API or you can... |
3,711,368 | 3,711,458 | Asynchronous threads in standard C++ | I wonder how could I implement an asynchronous call in standard C++.
I have a image/video processing program and I want to add another function/feature but I would like it to be run in a another thread or to be run asynchronously to the original thread.
I just want to notify the main thread when something happened in t... | The current C++ standard doesn't define such a thing, but C++0x does. That leaves a couple of choices. The cleanest is to probably use a current implementation that includes the C++ future class (and relatives). This seems to be exactly the sort of thing you're looking for. Depending on the compiler you're using, suppo... |
3,711,521 | 3,711,553 | Changing value of preprocessor symbol for testing | I am writing a dynamically growing string buffer. I have the following in a .c file.
#ifndef STRBUF_GROWTH_SIZE
#define STRBUF_GROWTH_SIZE 4096
#endif
My code uses this constant to do the reallocation of the buffer. Now in the tests, I need to set this value to a small one so that I can check the reallocation. I tried... | Preprocessing is done on a source-file-by-source-file basis (well, not quite, but it's close enough). A #define in one source file won't affect anything in another source file.
You'll either need to #define this in a header, which you can swap out with another header during testing, or you'll need to parameterise your... |
3,712,007 | 3,712,155 | Policies conversion works only with constructor | #include "stdafx.h"
#include <exception>
template<class T>
class NoCheck;
template<class T>
class EnforceNotNull
{
public:
//EnforceNotNull(const NoCheck<T>&){}//<<-----If this is uncommented it works
static void Check(T* p)
{
class NullPtrException : public std::exception
{
};
... | Your operator EnforceNotNull<T>() function is not const, so the compiler isn't including it in the set of possible conversion functions. Uncomment EnforceNotNull copy ctor or put a const on the above function and your code should work.
|
3,712,349 | 3,713,450 | boost.serialization - free version and base class implementation | I have a "generator" class that basically constructs its subclass. To use this thing I simply subclass it and pass it the correct parameters to build the object I want built. I want to serialize these things and there's no good reason to do it for each subclass since all the data is in the base. Here's what I've got... | Clarification why the problem happens:
boost::serialization has to ways of implementing the serialize function. As class method or (in your case) the non-intrusive way of defining a function in the boost::serialization namespace.
So the compiler has to somehow decide which implementation to choose. For that reason bo... |
3,712,379 | 3,714,193 | Return value of ifstream.peek() when it reaches the end of the file | I was looking at this article on Cplusplus.com, http://www.cplusplus.com/reference/iostream/istream/peek/
I'm still not sure what peek() returns if it reaches the end of the file.
In my code, a part of the program is supposed to run as long as this statement is true
(sourcefile.peek() != EOF)
where sourcefile is my if... | Consulting the Standard,
Returns:traits::eof() ifgood()isfalse. Otherwise,returnsrdbuf()->sgetc().
As for sgetc(),
Returns: If the input sequence read position is not available, returns underflow().
And underflow,
If the pending sequence is null then the function returns traits::eof() to indicate failure.
So yep,... |
3,712,708 | 3,713,036 | how C++ ensures the concept of base class and derived class | I would like to know how c++ ensures the concept layout in memory of these classes to support inheritance.
for example:
class Base1
{
public:
void function1(){cout<<"Base1"};
};
class Base2
{
public:
void function2(){cout<<"Base2"};
};
class MDerived: Base1,Base2
{
public:
voi... | When a MDerived* needs to be converted to a Base1*, the compiler adjusts the pointer to point to the correct memory address, where the members of this base class are located. This means that a MDerived* that is cast to a Base1* might point to a different memory address than the original MDerived* (depending on the memo... |
3,712,869 | 3,712,915 | C++ templates: calculate values and make decisions at compile time | Say you have a vector class that has a template length and type - i.e. vec<2,float>. These can also be nested - vec<2,vec<2,vec<2,float> > >, or vec<2,vec<2,float> >. You can calculate how deeply nested one of these vectors is like this:
template<typename T>
inline int depth(const T& t) { return 0; }
template<int N, t... | It's entirely possible. Try for example
template<int N, typename T, int M, typename U>
inline typename enable_if<is_deeper<T, U>::value, vec<N,T> >::type
operator +(const vec<N,T>& v1, const vec<M,U>& v2) {
return v1 + coerce(v2,v1);
}
template<int N, typename T, int M, typename U>
inline typename enable_if<is_de... |
3,712,908 | 3,755,038 | gcov: producing .gcda output from shared library? | Is it possible to produce gcov data files (.gcda files) by running an executable linked to a shared library built with the --coverage option?
Basically, I have the main library consisting of multiple c++ files compiled into one shared library and then a subdirectory called "test" containing a test program that links to... | I finally solved this problem by getting some help from the gcc guys. See the thread here: http://gcc.gnu.org/ml/gcc-help/2010-09/msg00130.html.
It turns out that the .gcda files were being put in the .libs directory since that's where the shared library (.so) files were. In order to get gcov to produce the output, I... |
3,713,704 | 3,713,738 | How to override operator <<? | hey, i have overridden operator<< and when i'm trying to use it in a print method (const) i'm getting an error :
the overriden operator :
ostream& operator <<(ostream& os, Date& toPrint)
{
return os << toPrint.GetDay() << "/" << toPrint.GetMonth() << "/" << toPrint.GetYear();
}
where i'm trying to use it :
void T... | You are using your operator<< in a const member function, thus m_treatmentDate is const (unless declared mutable). You need to fix your operator<< to take const arguments:
ostream& operator <<(ostream& os, const Date& toPrint);
Note that for this to work GetDay(), GetMonth() and GetYear() have to be const member funct... |
3,713,706 | 3,713,729 | C++ Add Object to Array | I need to instansiate an object and add it to an array. This is what I currently have in a method:
Row r;
rows[count] = r;
The problem here is r is on the stack and being removed after the function exits. I quick fix is to make r static but that is bad right? What should I do? (Sorry, complete C++ noob).
Edit: Removin... | The line rows[count] = r copies the object r to the element at index count in the array. After that, it doesn't matter what happens to r, the array is unaffected.
[Edit: OK, it matters indirectly what happens to r - since the copy is using something that r can delete.]
This is surprising if you're used to (for example)... |
3,713,744 | 3,713,753 | Does the boost library depend on the std C++ library? | We're needing to write small fast code on the windows platform and I know that boost in some instances has header only implementations. These need to be small for a reason, so we've been careful not to use the std C++ libraries actually because of size.
My question is, does using boost asio or system also haul in the ... | Of course, Boost just provides a layer of abstraction. It has to use the C++ STL library at some point. If you don't believe me, just check the code.
|
3,713,767 | 3,720,889 | Moving a player with Box2D | What is the proper way of moving a player in Box2D setting Player->ApplyForce() kind of feels like it lacks flexibility and control. What other ways might there be to do this?
Thanks
| SetPosition() could do it, but it really depends on what effect you're after.
|
3,713,784 | 3,719,602 | Boost Graph Library Undirected Graph No parallel edges enforcement | I'm using the Boost Graph Library to process an undirected graph, and declared my graph has
typedef property<vertex_index_t, int, property<vertex_name_t, string> > VertexProperty;
typedef adjacency_list<vecS, setS, undirectedS, VertexProperty > UndirectedGraph;
As you can see, the OutEdgeList is of the type std::set... | The problem was that the OutEdgeList is the first template parameter, not the second, so I was in fact using vecS and not setS.
|
3,714,041 | 3,714,054 | Why does this makefile execute a target on 'make clean' | This is my current makefile.
CXX = g++
CXXFLAGS = -Wall -O3
LDFLAGS =
TARGET = testcpp
SRCS = main.cpp object.cpp foo.cpp
OBJS = $(SRCS:.cpp=.o)
DEPS = $(SRCS:.cpp=.d)
.PHONY: clean all
all: $(TARGET)
$(TARGET): $(OBJS)
$(CXX) $(CXXFLAGS) $(LDFLAGS) $(OBJS) -o $(TARGET)
.cpp.o:
$(CXX) $(CXXFLA... | It's because the .d files are being -included unconditionally. As far as make knows, they could add dependencies or commands to the clean target. All included files are built first for this reason, otherwise you might get an incorrect or failed build. To disable this, you want to conditionally include the dependency fi... |
3,714,162 | 3,714,170 | Class inherited from class without default constructor | Right now I have a class A that inherits from class B, and B does not have a default constructor. I am trying the create a constructor for A that has the exact same parameters for B's constructor
struct B {
int n;
B(int i) : n(i) {}
};
struct A : B {
A(int i) {
// ...
}
};
but I get:
error: no matching f... | The constructor should look like this:
A(int i) : B(i) {}
The bit after the colon means, "initialize the B base class sub object of this object using its int constructor, with the value i".
I guess that you didn't provide an initializer for B, and hence by default the compiler attempts to initialize it with the non-ex... |
3,714,171 | 3,714,180 | Converting a std::list to char*[size] | for some reason I cannot explain, every single item in the character array...is equal to the last item added to it...for example progArgs[0] through progArgs[size] contains the value of the last item.
I cannot figure out what I'm doing wrong for the life of me. Any suggestions?
int count = 0;
char *progArgs[commandList... | You're assigning the same pointer (the address of the first element of the stack array item) to each element of progArgs, then repeatedly overwriting that memory. You can do:
progArgs[count] = strdup(t->c_str());
and get rid of the first two lines of the for body.
strdup allocates memory, so you will have to free eac... |
3,714,221 | 3,714,245 | Can someone explain the following strange function declarations? | std::thread f()
{
void some_function(); // <- here
return std::thread(some_function);
}
std::thread g()
{
void some_other_function(int); // <- here
std::thread t(some_other_function,42);
return t;
}
| Lines like:
void some_function();
simply declare a function which will be defined later. Functions don't necessarily have to be declared outside of function scope.
|
3,714,280 | 3,714,497 | C/C++ libraries for HTTP programming |
Possible Duplicate:
C/C++ - Any good web server library?
What well known C/C++ libraries are out there that could allow one to implement servlets, or at least provide most of the essentials for dealing with HTTP/CGI protocols such as http headers, error codes, cookies, GET/POST etc.
So far I have only found CPPSERV.... | One way to do this is to write your servlet as an Apache module - Apache itself then acts as the HTTP server-side library.
|
3,714,639 | 3,717,521 | Getting boost::function arity at compile time? | I need to make a decision in a BOOST_PP_IF statement based on the arity (parameter count) of a boost::function object. Is this possible?
boost::function_types::function_arity does what I'm looking for, but at runtime; I need it at compile time.
| For some reason my includes keep breaking but not in preview =[
#include <ostream>
#include <iostream>
#include <boost/function.hpp>
// Assume that you want to print out "Function is N-arity" for general case. But "nularity" for 0
template< int i >
struct DarkSide
{
template<class U>
void operator()(std::ostrea... |
3,714,649 | 3,715,867 | C++ Reading in words from a text file, word by word or char by char | I've been googling around and reading through my book and trying to write out code to read through a text file and process words out of it, one by one, so i can put them in alphabetical order and keep a count of how many words where used and much a word was used. I can't seem to get my GetNextWord() function to work pr... | Your logic is wrong. The inner loop runs as long as c doesn't change, and there's nothing in it that would change c.
Why are you having two loops anyway? I think you might be confused about whether that function is supposed to read the next word or all words. Try to separate those concerns, put them into different fun... |
3,714,808 | 3,714,817 | Forward declarations for variables? | I have some C code that I have to port to C++. The code has a structure
struct A {
...
struct A * myPtr;
}
And now two global arrays are declared and initialized like this:
//Forward declaration of Unit
struct A Unit[10];
struct A* ptrUnit[2] = { Unit, Unit+7 };
struct A Unit[10] = { { .., &ptrUnit[0] },
... | In C++, a variable declaration must be prefixed with extern:
extern A Unit[10];
// ...
A Unit[10] = { ... };
(Note that in C++ you can omit the leading struct.)
|
3,714,964 | 3,715,008 | How to convert from BYTE array to CString in MFC? | How can I convert a BYTE array in a CString in MFC?
| Try this - for eg: - If 'x' is your Byte array then -
BYTE x[5];
x[0] = 'A';
x[1] = 0;
x[2] = 'B';
x[3] = 'C';
x[4] = 0;
CString str( (LPCSTR) &x, sizeof(x) );
|
3,714,985 | 3,715,011 | How to properly cast an object? | I have a code,
class foo : public bar
{
public:
foo(){};
~foo(){};
};
class wu
{
public:
wu(const bar& Bar ) :
m_bar(Bar)
{};
~wu(){};
private:
bar m_bar;
};
int main()
{
foo tmpFoo;
wu tmpWu(tmpFoo);
}
Now my problem is, the code above will not compile and the error messa... | You must use the syntax m_bar(Bar) instead of m_bar = Bar in the wu class constructor. Also, remove the braces from the tmpFoo variable declaration, otherwise you will be declaring a function that returns a foo object and receives no arguments.
After your edit: I tried that code, and the problem it gave was that the b... |
3,715,034 | 3,715,056 | Where are literals stored in statement like this if( var == 'x')? | Say in a statement like this
char var;
if( var == 'x');
Do we allocate any memory for 'x' at first place?
If yes, which is it (stack/data)?
Thanks!
| The value 'x' may be stored directly in the code segment as part of the comparison instruction, or it may be stored in the code segment for an immediate load into a register, or in the data segment for an indirect load or compare. It is up to the compiler.
|
3,715,430 | 3,715,445 | Is there any concept in c++ like reflector in .Net? | i like to get code from c++ dll ,i know we easily get from .Net dll by reflector. Is there any method available in c++ for this?
Thanks In Advance
| C++ is compiled directly to machine code. There's no intermediary language as in .NET. There are some C++ disassemblers you may take a look at. Hex-Rays decompiler is particularly good.
|
3,715,729 | 3,715,913 | Heap corruption during SetClipboardData() | I'm not sure what is the root cause for getting such error(Heap Corruption) from the below code. When i step through the program, the TCHAR value is properly allocated and copied to the clipboard data. However, it crash when it proceed to SetClipboardData(...).
Can any guru help to spot the error?
Thanks in advance.
Er... |
_tcscpy_s(pchData, size, LPCTSTR(szText));
For Unicode wcscpy_s function, size parameter is size in words, and you pass size in bytes. This may cause memory corruption, because wcscpy_s fills all the buffer with 0xFD prior to copying, in order to catch such errors.
(thanks to sharptooth for exact information).
|
3,715,815 | 3,716,124 | C++ Memory Allocation | When using C++,
if there is a class:
class MyClass
{
char memory1bye;
int memory4bytes;
int another4bytes;
};
this class uses total of 9 bytes at memory… so if i do something like:
MyClass *t1;
This will give me a usable address for the Class, but will it allocate the 9 bytes? And will it call default co... |
As many people have said, the size of MyClass is implementation-dependent. In this case, because the class has no methods, you've basically got a struct so it is possible to make some reasonable guesses as to size. On a normal modern 32-bit machine without any unusual compiler flags, the size of the structure will be ... |
3,716,259 | 3,716,332 | How to acess COM port of remote system? | I Want to access the COM port present in the remote system from system. Any help would be appreciable.
I am using windows XP in both remote as well as local system.
| The com0com project, and especially the com2tcp application should help you.
In conjunction with the Null-modem
emulator (com0com) the com2tcp enables
to use a COM port based applications
to communicate with the TCP/IP based
applications. It also allows
communication with a remote serial
port via the TCP/... |
3,716,277 | 3,716,360 | Do rvalue references allow dangling references? | Consider the below.
#include <string>
using std::string;
string middle_name () {
return "Jaan";
}
int main ()
{
string&& danger = middle_name(); // ?!
return 0;
}
This doesn't compute anything, but it compiles without error and demonstrates something that I find confusing: danger is a dangling referenc... |
Do rvalue references allow dangling references?
If you meant "Is it possible to create dangling rvalue references" then the answer is yes. Your example, however,
string middle_name () {
return "Jaan";
}
int main()
{
string&& nodanger = middle_name(); // OK.
// The life-time of the temporary is extended... |
3,716,453 | 3,716,493 | Is it a good practice to make constructor explicit | When designing a public API, is it a good practice to make the constructor as explicit?
class A {
public:
//explicit A(int i){}
A(int i){}
};
void fun(const A& a) {}
int main() {
// If I use explicit for A constructor, I can prevent this mistake.
// (Or shall I call it as feature?)
fun(10);
}
Or ... | The constructor should be explicit, unless an implicit conversion makes sense semantically (e.g. what is the meaning of converting an int to an A?). Less typing should not be the criterion to guide that decision. Think about readability (which is the main argument for implicit casting) and how well your code is to unde... |
3,716,799 | 3,716,919 | Partial specialization of function templates | Does anyone know whether, in C++11, function templates can be partially specialized?
| No, they can't. The draft C++0x standard has a section (14.5.5) on class template partial specialisations, but no mention of function template partial specialisations.
|
3,716,821 | 3,716,885 | Organisation of compiler dependency paths to external libraries | I my current team we organize the dependencies to external libraries headers in the project settings like that:
Compiler Settings->Additional Includes:
d:\src\lib\boost_1_43
d:\src\lib\CxImage_6_00
...
As you can see, we include the exact library version number in our paths.
The advantage of this method is that we alwa... | You can use property sheets to manage common project properties easily.
My suggestion would be to set up user macros organized something like so:
$(DependenciesPath) => d:\src\lib\
$(BoostPath) => $(DependenciesPath)boost_1_43\
$(CxImagePath) => $(DependenciesPath)CxImage_6_00\
Then, in your project ... |
3,717,107 | 3,719,587 | Should I Use Single Connection or Multiple Connections with QSqlDatabase | I have dependent and independent classes, I need to create database connections in these classes. As I understand from Qt documentation, if I create connections in default way, all of them use same connection.
Should I create different database connections for different classes, or should I use same database connection... | I'm not sure why @Dummy00001 logged his response as a comment rather than an answer, but I concur with him. If you aren't going to be working with the database in a parallel fashion, you don't need multiple connections, and they will, in fact, be wasteful of resources both in your client library and on the server.
|
3,717,427 | 3,717,635 | How can I use 3-dimensional data as a class property? | It's been a long time since I worked with C++, but I have a class that uses 3-dimensional data and I can't figure out how I can make this work. I need the sizes of the dimensions to be defined in the constructor. I tried this in the header:
class CImage
{
public:
float values[][][];
...
}
and this in the construct... | The program crashes when accessing that vector because it is empty, i.e. there are no elements at those indexes.
The best way to go about this is to make a linear, one-dimensional, vector (or even an array), and access it with a pair of operator()'s, see C++FAQ Lite for details. Or use boost::multi_array.
For example:
... |
3,717,474 | 3,717,508 | Problem understanding explicit constructor in C++ | After reading this thread
What does the explicit keyword mean in C++?
I made up this program
class MyClass
{
public:
explicit MyClass(int a)
{
cout<<"Int was called"<<endl;
val = a;
}
MyClass(char *a)
{
cout<<"Char was called"<<endl;
val = atoi(a);
}
MyClass(const MyClass& copy)
{
... | Explicit constructor will not allow you to do something like "implicit conversion", e.g. when initializing an object:
MyClass d = 4;
or when calling a function with parameters:
void foo( const MyClass& param);
...
foo( 4);
In your case, there is a conversion from char to int before calling the explicit constructor... |
3,717,497 | 3,717,667 | Compiler detection of returning reference to local variable | I've just been bitten by a nasty undefined behavior due the returning a reference to a local variable.
We know it's evil, and generally the compiler prints a nice warning to tell us so... well gcc (3.4.2) does not seem to push the checks too far though.
std::string get_env_value(std::string const& key);
std::string co... | The standard does not cover [2]. It allows an rvalue to be bound to a const reference, but that doesn't allow you to return a const reference and have the lifetime of the rvalue it is bound to extended as well.
And true, static analysis could catch this, but as always it's a trade-off. C++ compilation is slow enough as... |
3,717,499 | 3,717,524 | copy and call function | I'd like to copy and call a function, but the code below segfaults when calling the buffer. What do I have to change? (Linux, x86)
#include <string.h>
#include <malloc.h>
#include <stdio.h>
int foo () { return 12; }
void foo_end () {}
int main () {
int s = (unsigned long long) foo_end - (unsigned long long) foo;
... | Potentially you're using an OS which does not grant execute permission to data segments.
Some environments will protect data pages against execution, to avoid various types of security problems (or exploits for them).
Consider calling mprotect() to enable execute for that page and report what happens.
|
3,717,538 | 8,021,226 | why is my std::string being cut off? | I initialize a string as follows:
std::string myString = "'The quick brown fox jumps over the lazy dog' is an English-language pangram (a phrase that contains all of the letters of the alphabet)";
and the myString ends up being cut off like this:
'The quick brown fox jumps over the
lazy dog' is an English-language
... | Of course it was just the debugger cutting it off (xcode). I'm just getting started with xcode/c++, so thanks a lot for the quick replies.
|
3,717,839 | 3,717,858 | Undefined reference to a local class | I've just played with qjson library and got "undefined reference" error. This is the code:
#include <qjson/qobjecthelper.h>
#include <qjson/serializer.h>
class Person: public QObject {
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(Gender gender READ gender WRITE setGender)
Q_EN... | You have only declared the methods of the class. You also need to define (i.e. implement) them. At the moment, how should the compiler know the constructor of Person is supposed to do?
|
3,717,953 | 3,717,972 | compare char* with string macro | I have the following code:
#define INPUT_FILE "-i"
int main(int argc, char* argv[]) {
....
}
is there any way in C++ to compare between strings in argv[] and INPUT_FILE?
I tried
strcmp(argv[1],INPUT_FILE)
It compiles but return false each time.
Thanks !
| strcmp returns 0 if there is a match.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.