question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,640,669 | 4,640,722 | How string accepting interface should look like? | This is a follow up of this question. Suppose I write a C++ interface that accepts or returns a const string. I can use a const char* zero-terminated string:
void f(const char* str); // (1)
The other way would be to use an std::string:
void f(const string& str); // (2)
It's also possible to write an overload and acce... | For taking a parameter I would go with whatever is simplest and often that is const char*. This works with string literals with zero cost and retrieving a const char* from something stored in a std:string is typically very low cost as well.
Personally, I wouldn't bother with the overload. In all but the simplest cases ... |
4,640,985 | 4,641,013 | Making a class abstract without any pure virtual methods | I have a class which is to listen to mouse events. However, I do not want to force the user to implement any specific one, but I do want to make it clear that they must inherit it.
Is there a way to do this?
Thanks
| You can declare a pure virtual destructor, but give it a definition. The class will be abstract, but any inheriting classes will not by default be abstract.
struct Abstract
{
virtual ~Abstract() = 0;
};
Abstract::~Abstract() {}
struct Valid: public Abstract
{
// Notice you don't need to actually overide ... |
4,640,989 | 4,640,999 | How do static member variables affect object size? | I'm wondering how static member variables are typically implemented in languages like C++ and if their use affects the size of instantiated objects.
I know that a static members are shared by all instances of that class, but how is it shared? If it affects object size, would having 10 static variables add more size th... | In C++, static members don't belong to the instances of class. they don't increase size of instances and class even by 1 bit!
struct A
{
int i;
static int j;
};
struct B
{
int i;
};
std::cout << (sizeof(A) == sizeof(B)) << std::endl;
Output:
1
That is, size of A and B is exactly same. static members are m... |
4,640,994 | 4,641,024 | overloaded operator << on ofstream concatenation problems | I have the following code:
struct simple
{
simple (int a1, int a2) : member1(a1), member2(a2) {}
int member1;
int member2;
};
std::ofstream &operator << (std::ofstream &f, const simple &obj)
{
f<<obj.member1<<", "<<obj.member2;
return f;
}
int main(int argc, const char *argv[])
{
std::ofstream... | On the line :
f << "label: " << s;
Because the first call to operator<< returns a std::ostream &, the second fails to compile : the left operand to the operator is not of type std::ofstream anymore and your overload is not found.
You should really use the second signature, as I see no reason for restricting your type ... |
4,641,049 | 4,642,677 | Creating serializeable unique compile-time identifiers for arbitrary UDT's | I would like a generic way to create unique compile-time identifiers for any C++ user defined types.
for example:
unique_id<my_type>::value == 0 // true
unique_id<other_type>::value == 1 // true
I've managed to implement something like this using preprocessor meta programming, the problem is, serialization is not ... | A while back I added a build step to one project of mine, which allowed me to write @script_name(args) in a C++ source file and have it automatically replaced with the output of the associated script, for instance ./script_name.pl args or ./script_name.py args.
You may balk at the idea of polluting the language into n... |
4,641,243 | 4,641,296 | Symboling functions without PDBs |
Suppose I have a function called "Overflow" in a DLL called "Overflow.dll" but I don't have its PDBs.
I know I can get the address it starts in with "GetProcAddress", but can I get somehow the address where it ends or its size?
(C++ in windows)
The reason I ask this is that I have an address and I want to know if it i... |
So I assume (and please correct me if I'm wrong)
I'm "correcting". The issue is that it's extremely unlikely that your function has no function calls inside of itself. For example, the position could be inside of a printf call called by your function, but the instruction pointer would not be in your function itself.
... |
4,641,364 | 4,642,538 | Using template specialization in C++ | How can I write a function using template specialization that has 2 different input types and an output type:
template <class input1, class input2, class output>
and return the sum of the 2 numbers (integers/doubles). However, if I get 2 integers I want to return an integer type but for any other combinations of integ... | It is possible for the return type of a function template to depend on the types of the template parameters. In your case, you can do something similar to:
template <typename L, typename R>
struct sum_traits { typedef double return_type; };
template <>
struct sum_traits<int, int> { typedef int return_type; };
templat... |
4,641,398 | 4,641,601 | Why can't I dynamic_cast "sideways" during multiple inheritence? | The following code throws std::bad_cast
struct Foo {
void foo () {}
};
struct Bar {
Bar () {
dynamic_cast <Foo &> (*this) .foo ();
}
virtual ~ Bar () {}
};
struct Baz : public Foo, public Bar {
};
int main ()
{
Baz b;
}
I remember once reading how dynamic_cast has implementation performa... | There are no virtual functions in Foo, so dynamic_cast is perfectly obliged to fail. There needs to be a virtual function. It's also a bad idea to do so during construction, as you're going to run into construction order issues.
|
4,641,639 | 4,642,106 | How to Query process names under low integrity process? | I'm writing a BHO and I'd like to execute an external process.
If the OS is vista or greater the user may be in protected mode, making my BHO running under a low integrity process.
The external process I'm trying to execute is listed in the IE's Elvation Policy list making it running under normal integrity.
I'd like to... | Well,
CreateToolhelp32Snapshot solved it, it maps every process no matter what it's integrity.
The PROCESSENTRY32 struct has the executable file and that's all i needed.
|
4,641,736 | 4,641,789 | Is there such a thing as a C++ interpreter? |
Possible Duplicate:
Have you used any of the C++ interpreters (not compilers)?
Hi,
I am currently learning C++ and a beginner in programming in general. I've been trying to write some code to a few programming problems from the book I'm using. What I find is that often I make mistakes in what I write and those mista... | CINT is a c & C++ interpretter that accepts nearly all valid C++. Unfortunately many Linux distros do not offer it, and you'll probably have to build it from source... and that is a non-trivial task.
|
4,641,809 | 4,641,839 | How should I indent do nothing initialization list constructors? | Example: Thread::Thread:
class Thread
{
Process * parent_;
unsigned __int32 id_;
void * entryPoint_;
public:
Thread(Process * parent, unsigned __int32 id, void * entryPoint) :
parent_(parent),
id_(id),
entryPoint_(entryPoint)
{
}
unsigned __int32 GetId() const
{
... | I always put empty blocks on a single line – i.e. { } (notice the space!).
Furthermore, I usually put the colon and commas in front of the initialization list members instead of after – this makes adding members later on easier.
Thread(Process * parent, unsigned __int32 id, void * entryPoint)
: parent_(parent)
... |
4,641,812 | 4,642,487 | c++ exception from constructor core dumps on freebsd but not on linux or mac os x | Why does the program listed below run on mac osx and linux but not on freebsd?
The freebsd core dumps after the exception is thrown with the following message:
terminate called after throwing an instance of 'ObjectException'
what(): error not allowed
[1] 28946 abort (core dumped) ./bin/main
On all three platfor... | Works for me on FreeBSD 8.1-RELEASE-p2 and OSX 10.6.6.
You could have a bad version of libstdc++ in your search path. When I link on FreeBSD 8.1, I get the following output from ldd:
janm@midgard: test3 $ ldd a.out
a.out:
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x800649000)
libm.so.5 => /lib/libm.so.5 (0x800... |
4,641,817 | 10,116,591 | Blob extraction in OpenCV | I'm using OpenCV to filter an image for certain colours, so I've got a binary image of the detected regions.
Now I want to erode those areas and then get rid of the smaller ones, and find the x,y coordinates of the largest 'blob'
I was looking for recommendations as to what the best library would be to use? I've seen c... | I'm late to the party, but I'd just like to chime in that there is a way to do connected components in opencv, it's just not mainlined yet.
Update: It is mainlined, it's just been stuck waiting for 3.0 to release for multiple years. Linky to documentation
See http://code.opencv.org/issues/1236 and http://code.opencv.... |
4,642,014 | 4,642,037 | Variable length argument list - How to understand we retrieved the last argument? | I have a Polynomial class which holds coefficients of a given polynomial.
One of its overloaded constructors is supposed to receive these coefficients via variable argument list.
template <class T>
Polynomial<T>::Polynomial(T FirstCoefficient, ...)
{
va_list ArgumentPointer;
va_start(ArgumentPointer, FirstCoe... | In general, no, there's no way to know when you've hit the last argument and you'll need to provide some sort of sentinel. Variable-length argument lists are inherently unsafe for this reason; there's no way to statically check that all the arguments have been received correctly, or that they have the right types, etc... |
4,642,079 | 4,642,127 | Function signature-like expressions as C++ template arguments | I was looking at Don Clugston's FastDelegate mini-library and noticed a weird syntactical trick with the following structure:
TemplateClass< void( int, int ) > Object;
It almost appears as if a function signature is being used as an argument to a template instance declaration.
This technique (whose presence in FastDel... | With regards to your first question - about the type int(char, float) - this is a valid C++ type and is the type of a function that takes in a char and a float and returns an int. Note that this is the type of the actual function, not a function pointer, which would be an int (*) (char, float). The actual type of any... |
4,642,274 | 4,642,298 | Textfiles C++ Editing the very first line | Example of Textfile:
5 <- I need to edit this number.
0
1
0
6
(Sample Code Not Whole Program)
#include <fstream>
#include <iostream>
using namespace std;
int main() {
int i;
cin>>i;
std::fstream file("example.txt", std::ios::in | std::ios::out | std::ios::app);
file.seekp(0);
file << i;
return 0;
}
W... | You have opened the file in a mode that requests that all new data is appended to the end of the file (std::ios::app). Don't specify that flag if you don't want to always append.
Note that you will encounter problems if the new line you're writing is not exactly the same length as the existing line. In the case where i... |
4,642,339 | 4,642,436 | Trimming a vector of strings | I have an std::vector of std::strings containing data similar to this:
[0] = ""
[1] = "Abc"
[2] = "Def"
[3] = ""
[4] = "Ghi"
[5] = ""
[6] = ""
How can I get a vector containing the 4 strings from 1 to 4? (i.e. I want to trim all blank strings from the start and end of the vector):
[0] = "Abc"
[1] = "Def"
[2] = ""
[3] ... | How about this, with a predicate:
class StringNotEmpty
{
bool operator()(const std::string& s) { return !s.empty(); }
};
Now to trim:
vec.erase(std::find_if(vec.rbegin(), vec.rend(), StringNotEmpty()).base(), vec.end());
vec.erase(vec.begin(), std::find_if(vec.begin(), vec.end(), StringNotEmpty()));
There might be ... |
4,642,468 | 4,642,514 | Determining if types alias to the same underlying type in C++ | I'd like to write a templated function which changes its behavior depending on template class types passed in. To do this, I'd like to determine the type passed in. For example, something like this:
template <class T>
void foo() {
if (T == int) { // Sadly, this sort of comparison doesn't work
printf("Template par... | By using the power of partial specialization, this can be done at compile time:
template<class T, class U>
struct is_same_type
{
static const bool value = false;
};
template<class T>
struct is_same_type<T, T>
{
static const bool value = true;
};
template <class T>
void foo()
{
if (is_same_type<T, int>::va... |
4,642,497 | 4,642,529 | Passing a member function to for_each in C++03 (no boost, no c++11) | The "solution" below compiles but it is not what I want. I would like to pass the put member function to for_each and not *this. Using boost is NOT an option. Can this be solved within C++03?
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
class Wheel { };
class Car {
public:
v... | Yes it can, using a combination of the mem_fun and bind1st templates:
void process(const vector<Wheel>& wheel) {
for_each(wheel.begin(), wheel.end(), bind1st(mem_fun(&Car::put), this));
}
The call to mem_fun creates a new function object that takes in two arguments - a Car* to act as the receiver and a Wheel, then... |
4,642,499 | 4,642,520 | Template specialization for C-style string | I'm having difficulty getting the correct syntax for a template specialisation which accepts a regular c-style string. For example
namespace RubyUtils
{
template<class T> VALUE toValue(const T& v);
};
template<> VALUE toValue(char const* & v)
{
return toValue<string>(v);
}
and then at the call site
return Rub... | I think that the problem you're encountering is probably related to the fact that you've defined two templates - one inside of the namespace, and one out. The error is likely due to this confusion.
But more importantly, as a general rule, you do not want to specialize function templates. Template specialization for f... |
4,642,619 | 4,642,876 | tolua++: Adding lua functions to a C++ class that has been exported to Lua | I am using tolua++ to export some C++ classes to Lua.
My understanding that each class is 'implemented' on the lua side, as a lua table. I am wondering if it is possible therefore, to add new (Lua) methods to the C++ object table so that I can achieve the effect of adding new methods to the C++ class.
Assume that I am ... | Yes, It is possible to add new methods to an existing exported class.
Foobar is just a plain table, so you can attach methods onto it as you would any other table. [1]
Foobar["extra_method"] = function (self, arg1, arg2) print(arg1, arg2) end
and now you can do:
Foobar:extra_method(1,2)
and 1 2 will be displaye... |
4,642,672 | 4,642,705 | Strange behaviour of the typeid operator? | Using XCode 3.2.3 (64-bit), I get following strange output. What am I doing wrong?
#include <iostream>
#include <typeinfo>
struct student {
};
int main()
{
int i;
student obj;
std::cout << typeid(i).name() << "\n";
std::cout << typeid(obj).name() << "\n";
return 0;
}
Output:
i
7student
... | What's going on is nothing special. Just that typeid doesn't promise to return the "original" name of the type, but just a name.
The function returns an implementation-defined string, which, if you're lucky, is recognizable, but it makes no promise of that.
|
4,642,702 | 4,642,746 | Wrapping unmanaged C++ with C++/CLI - a proper approach | as stated in the title, I want to have my old C++ library working in managed .NET. I think of two possibilities:
1) I might try to compile the library with /clr and try "It Just Works" approach.
2) I might write a managed wrapper to the unmanaged library.
First of all, I want to have my library working FAST, as it was ... | First of all, forget about Managed C++. Use C++/CLI.
The difference is that Managed C++ was Microsoft's first attempt at extending C++ to work with .NET, and honestly, it was all kinds of horrible.
So they gave up on that, and designed C++/CLI instead, which works much better.
Second, valid C++ code should just work if... |
4,642,836 | 4,643,242 | How to efficiently unpack float, int16, int32, etc. data from void* array in C++? | I’ve got an array of PCM data; it can be 16-bit, 24-bit packed, 32-bit, etc. It can be signed, or unsigned, and it can be 32 or 64-bit floating point. It is currently stored as a void** matrix, indexed first by channel, then by frame. The goal is to allow my library to take in any PCM format and buffer it, without requ... | This one will match typecodes to casting functions. The basic idea is that it creates a set of tiny conversion functions for each type, and an array of function pointers, and then indexes into that array based on the data format in order to find the correct conversion function to call.
Usage example:
int main ()
{
... |
4,642,934 | 4,643,691 | Porting a select loop application to Android with NDK. Design question | I have an network application which uses a select loop like this:
bool shutdown=false;
while (!shutdown) {
[do something]
select(...,timeout);
}
THe main loop cannot work like this in an Android application anymore since the application needs to receive Intents, need to handle GUI, etc.
I think I have basi... | Based on limited info provided, I can think of following approach:
A loop can run in a separate thread with two options:
a) look for gui led changes (based on value of a global native state variable say, native_app_state, of enum type)
b) something happens that triggers a callback to Java
You can have separate native ... |
4,643,137 | 4,643,150 | Looking for a C++ library to automate application updates | I have created a program in C++ but I want that the program download and install an update every month automatically and invisibly to the user. How can I do that ?
| Try Omaha from Google. They use it for most of their own products like Chrome.
|
4,643,179 | 4,643,352 | Running Qt Unit tests | Looking at Qt's site, and at another Stackoverflow answer because I don't want to create a separate project for each class I want to test, I've come up with the following code:
testqstring.h
#ifndef TESTQSTRING_H
#define TESTQSTRING_H
#include <QtTest/QTest>
class TestQString : public QObject
{
Q_OBJECT
private ... | Add:
CONFIG += qtestlib
to the .pro file to get qmake to link in the qtest library.
|
4,643,425 | 4,643,435 | Memory allocation in C++ | I am confused about the memory allocation in C++. Can anyone guide me as to where each of the variable in the below snippet is getting allocated. How can I determine what is getting allocated on stack and what gets allocated on heap. Is there any good web reference for learning this.
class Sample {
private:
... | If it's created via new, it's in the heap. If it's inside of a function, and it's not static, then it's on the stack. Otherwise, it's in global (non-stack) memory.
class Sample {
private:
int *p;
public:
Sample() {
p = new int; // p points to memory that's in the heap
}
... |
4,643,430 | 4,643,837 | Allocating memory by size zero in c++? | int a = 10;
int *p = new int[0];
p = &a;
cout << *p << endl;
In c++, what happens if allocate memory size by zero?
after allocation I get valid memory pointer, and prints valid number.
But I think new operator should return something like FAILD or NULL.
Can anybody explain detail?
|
In c++, what happens if allocate memory size by zero?
A zero sized array is valid.
You just can de-reference any members.
This is why the Greeks spent such a long time debating it thinking about zero as a number. But we can thank India at its great minds for eventually bringing zero as a number 0. It took them fore... |
4,643,473 | 4,643,946 | Creating a custom window for GLUT? | Is there a method to create/specify a custom window for GLUT instead of using the glutCreateWindow method? I'd like to modify certain elements of the window, such as removing the border, possibly rounding the corners, etc.
There doesn't seem to be any built-in functions to set a certain HWND handle as the targetted GLU... | Glut, and OpenGL which Glut is built on, are intended to be crossplatform. Every platform has it's own ideas about what makes a window. To work around this OpenGL has it's own concept of windows, or rendering contexts. A rendering context is a chunk of memory where a DIB (Device Independent Bitmap) is rendered, which g... |
4,643,713 | 4,643,721 | Returning a reference to a local variable in C++ | Is the following code (func1()) correct if it has to return i? I remember reading somewhere that there is a problem when returning a reference to a local variable. How is it different from func2()?
int& func1()
{
int i;
i = 1;
return i;
}
int* func2()
{
int* p;
p = new int;
*p = 1;
return p... | This code snippet:
int& func1()
{
int i;
i = 1;
return i;
}
will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it... |
4,643,800 | 4,643,863 | different types of DLLs on windows platform | There are several type of dlls found on windows platform
Old style native dll
COM dll
.NET dll
Are there any more dll types that I am missing in list above? Also what is the difference between each of these?
TIA
| If you disregard what a DLL is used for, then there's only one type of 32-bit DLL.
It has PE (Portable Executable) format, and it exports functions and data, plus resources.
If you distinguish between different kinds of content, then there are an unbounded number of different "types" of DLLs. For example, a DLL might c... |
4,643,851 | 4,643,880 | Putting classes inside namespaces | I see that Qt puts a class inside the Ui interface like this:
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
...
Is this method the same as enclosing the entire class inside the namespace? It certainly looks cleaner.
| No, in your example Ui::MainWindow is a different class than the MainWindow class defined in the global namespace.
Behold:
namespace Ui {
class MainWindow;
}
class MainWindow
{
};
int main()
{
Ui::MainWindow mw; // fails due to incomplete type
}
This code won't compile, since Ui::MainWindow is an incomplete... |
4,643,953 | 4,644,058 | class function that generates its own objects | I want to write a class for some use. I want to call a function (say generate) of this class which will generate two objects of this same class. These two objects will call other function of the class.
Can anyone tell me how to do this?
I want it in C++
Class Example{
public:
generate();
other_func();
}
int main()
{... | Well, from your description it would sound very easy:
struct Example
{
public:
static void generate() { Example e1, e2; e1.other_fun(); e2.other_fun(); }
void other_fun() { }
};
|
4,644,296 | 4,644,322 | Can't assign an object to a volatile object | I want to assign an object to volatile object in the same type, but failed to do so with compiler error. How to change the program to make it? Besides to make it to work, why i can't do it directly?
I used Visual Studio 2010 as compiler here.
class A
{
public:
};
int _tmain()
{
A a;
volatile A va;
va = a; ... | You need to define an assignment operator function for A with the volatile qualifier.
class A
{
public:
volatile A& operator = (const A& a) volatile
{
// assignment implementation
}
};
If you don't define an assignment operator for a class, C++ will create a default assignment operator of A& ope... |
4,644,354 | 4,644,416 | Managing memory of polymorphic timed events with DLL | Here is my issue.
My Gui library that I made supports timed events. Basically, I have a class called TimedEvent which users inherit from. They then do:
addTimedEvent(new DerivedTimedEvent(...));
However given the nature of timed events, I manage the memory afterwards.
So when the timed event has done its thing, my lib... | Try getting a Dellocator Functor object as construction parameter for your TimedEvent class. Now every client creating a derived class is expected to provied a Dellocator which you can call while deleting the object. You should also have default dellocator functor which simply deletes as a special case.
class base;
cl... |
4,644,410 | 4,644,437 | Can static member function of base class call its derived class object? (C++) | Can static member function of base class call its derived class object?
| Think of static member-function as some non-member function. So yes. Whatever non-member function can do, static member-function can do the very same thing!
|
4,644,489 | 4,644,538 | Will the following cause problems with memory? | Say I have the following in a DLL implementation (eg, it would have a cpp file):
class Base
{
protected:
Something *some;
public:
virtual void init()
{
some = new Something();
}
virtual ~Base()
{
delete some;
}
};
Then in my exe I make:
class Derived : public Base
{
publi... | I think you need to write ~Derive() like this
~Derived()
{
delete some;
some = 0; //this is must; so that `delete some` in ~Base() works perfectly;
//note `delete (void*)0` is fine in C++!
}
Explanation :
Why you need to write this even though the ~Base() does the same thing (it looks it does the same thing) ... |
4,644,618 | 4,646,583 | problem in boost-interprocess library | std::pair<int*, std::size_t> p = managed_shm.find<int>("Integer");
can someone provide me with the definition of this find method.
| If you follow the code in the boost headers you'll find it, here is the starting point:
class basic_managed_shared_memory in boost/interprocess/managed_shared_memory.hpp (version 1.4.5 is what I checked, you've not specified your version!)
|
4,644,649 | 4,644,845 | How to disable CComboBox mfc keyboard navigation? | How i can disable CComboBox mfc keyboard navigation, i need when i press key on keyboard with open dropdown list, item must not selecting. Thanks!
| If you really just mean: "how do I disable the control from being changed?", then just call the EnableWindow method on the CComboBox.
But if you really mean you just want to block keyboard messages from hitting the control, then use window subclassing to swallow keyboard messages. (Don't confuse the term "window subcl... |
4,644,718 | 4,644,749 | Will this memory issue happen if I instance a DLL class? | There is something I'm unclear about regarding DLL's and different versions of the runtime.
I know that if for example, in my DLL I had a function like this:
void deletePointer(int *something)
{
delete something;
}
if something had been allocated using new in my main() function, this could cause a problem. Where I'... | Yes that could cause a problem. What you need to do is simply free allocated memory in the place you allocated it. This might mean you need to implement methods to create and delete the class instances within the DLL; for example if you wanted the DLL to create/destroy instances of Base, then:
class Base
{
static... |
4,644,753 | 4,644,783 | C++ dynamic_cast - polymorphic requirement and downcasting | In the following code, while constructing obj in case 1, we construct a derived class object too, but its member functions are just inaccessible to obj. So while downcasting (i.e., in case 2), using obj as source, we have the constructed derived in it already. Why would obj need to be polymorphic?
If I confused you wit... | From 5.2.7/1 [expr.dynamic.cast] :
The result of the expression dynamic_cast<T>(v) is the result of converting the expression v to type
T.
[...]
If T is "pointer to cv1 B" and v has type "pointer to cv2 D" such that B is a base class of D, the result is a
pointer to the unique B sub-object of the D object pointed ... |
4,644,766 | 4,644,849 | DOs and DON'Ts of a programming class? | Disclaimer: I apologize if this is too subjective and perhaps it may be better suited for programmers.stackexchange but I'll try my luck here first.
I'm in need of some advice that has made you successful in a college-level programming course (in my case, C++ and Java). I would especially appreciate it if professors ... | I hope this will be of some help to you - I used to head TA a CS course at an Ivy League college, which mean I wrote the mark schemes and grading guidelines.
Firstly, everyone does things differently, and in all honesty grading code is as subjective as grading an essay (this always surprises students starting out, bec... |
4,644,862 | 4,644,892 | Best practices: successfully merge two software? | Let's imagine the situation:
Two PC software, two development team, two different technology (different programming language), two sets of features, but ONE objective !
I'd like to know your TOP 3 things to do first before deciding (or not) to merge the software.
My first (unsorted) ideas: Meet the other team, compare ... | It sounds like company A has merged with company B and has two pieces of software that do the same thing but have been coded separately.
If this is the case, my advice is not to merge them at all (they're different technologies as you say. Whilst not impossible, you'll be spending a hell of a lot of money doing this).... |
4,644,866 | 4,644,887 | partial specialization of the templates in c++ | is it possible to do in c++ something like that:
template<class T1, class T2>
class A<T1*, T2> {
T1* var;
T2 var1;
};
template<class T1, class T2>
class A<T1, T2*> {
T1 var;
T2* var1;
};
Actually I want to know if I can reach template overloading, when two classes have the same name but differen... | That's known as partial template specialization
template<class T1, class T2>
class A;
template<class T1, class T2>
class A<T1*, T2> {
T1* var;
T2 var1;
};
template<class T1, class T2>
class A<T1, T2*> {
T1 var;
T2* var1;
};
Of course, you need a third one for A<T1*, T2*> to play safe. Otherwise you w... |
4,645,221 | 4,645,295 | Self operator override - Return by reference or return by copy | Consider the following code?
I was wondering, if I change it from (Function body still the same)
error_code& operator|=(const error_code &e)
to
error_code operator|=(const error_code &e)
Is there any potential bug that might possible occur? The only difference I see is, it will perform an extra copy operation, other ... |
Is there any potential bug that might possible occur?
Yes. This won't work as expected anymore:
(ec |= x) = y;
Now, this is a silly piece of code, no doubt about that, but
it does work for other types and
there might be other cases where this difference matters.
For example, if your class error_code will have ... |
4,645,458 | 4,645,722 | Defining a static array into a C or C++ source file | I know this is a question that every programmer should know, but I do not know. Long time no C programming and I've forgotten a lot of things.
My question is:
I have three huge static arrays defined inside a header file. Someone told me that It's much better to declare them as extern in the header file, and define them... | static and extern at the same time makes no sense. static at file scope makes the array inaccessible by other files, while extern tells the compiler that your array is defined somewhere else.
You can do what 321008 suggests, except that you don't declare your arrays static which is illegal C and C++. That gives you thr... |
4,645,537 | 4,646,088 | Linking Boost gives me error | When trying to compile my solution with VS2010 I'm getting a compiler error:
"error LNK1104: cannot open file 'libboost_unit_test_framework-vc100-mt-gd-1_45.lib'"
I've tried to look for this file on hard drive but with no luck.
Why am I getting this error and how can I fix it?
| you need to take precompiled Boost libraries for your system, e.g. from boostpro.com or build Boost yourself. Then add a path to Boost .lib's to your Linker paths
|
4,645,567 | 4,645,733 | In C, assignment of function pointer to appropriately-typed variable gives "cannot convert ... in assignment" | Take the following C/C++ code:
#include <stdlib.h>
int inc(int i) { return i+1; } // int→int, like abs()
// baz is bool→(int→int)
int (*baz(bool b))(int) { return b ? &abs : &inc; }
int main() {
int (*foo(bool))(int); // foo is &(bool→(int→int))
foo = baz;
}
Attempting to compile this (gcc or g++) gives:
$ g++... | The code is in fact wrong. The problem is that this line:
int (*foo(bool))(int); // foo is &(bool→(int→int))
... doesn't mean what you think it means. It's interpreted as a declaration of a function named "foo". That makes perfect sense. Think about it - if you had wanted to forward declare "baz", you would have ... |
4,645,687 | 4,645,892 | Linked List implementation- Program crashing | I was developing a generic linked list. Although the compiler doesn't give any error but on running the program, it just crashes. I haven't been able to figure out what's wrong but since I am trying insert method of the list in main, the problem is somewhere there itself. Here's the code in List.h
#include<cstdlib>
en... | What happens in your main function is:
Construct list; success.
Try to insert at position 1, which fails with range_error because position>count. If you choose to return error codes, you should always check for them.
Destroy list. This segfaults because head is NULL when you try to dereference it with Node<List_entry>... |
4,645,705 | 4,645,727 | Vector erase iterator | I have this code:
int main()
{
vector<int> res;
res.push_back(1);
vector<int>::iterator it = res.begin();
for( ; it != res.end(); it++)
{
it = res.erase(it);
//if(it == res.end())
// return 0;
}
}
"A random access iterator pointing to the new location of the element tha... | res.erase(it) always returns the next valid iterator, if you erase the last element it will point to .end()
At the end of the loop ++it is always called, so you increment .end() which is not allowed.
Simply checking for .end() still leaves a bug though, as you always skip an element on every iteration (it gets 'increm... |
4,646,717 | 4,646,759 | c++ allocate array syntax question | You can write like this:
int test[] = {1,2,3,4};
but what if you want to use a pointer and allocate it with new?
int *test2;
test2 = new int[]{1,2,3,4};
This does not work, what is the syntax or is it possible?
| This is one of the short-comings of current standard C++. Initialization is not uniform. Your best hope is uniform initialization in C++0x, but for the mean while you can assign the values after creating the array, e.g.
int *test2;
test2 = new int[4]; // Note that you still have to specify the size in C++0x
test2[0] = ... |
4,646,750 | 4,646,771 | Build C++ Projects with Makefile using Visual Studio 2008 | I downloaded cpptest from internet, and I want to build it using Visual Studio 2008.
The problem is that instead of .sln and vcproj file, Makefile.am is distributed, and I believe that all the all the necessary included file is included in the Makefile.am.
How to use Makefile.am to generate VS project files? I tried t... | the visual studio project files for cpptest are in the win directory, not in the src directory where the makefile is..
edit
makefiles are meant to be used with GNU make. If you want that on windows, you can look at Mingw, GnuWin32 or Cygwin. But they also require gcc for compiling, so you won't really be using VS.
Howe... |
4,646,937 | 4,647,512 | Static library with dependencies | e.exe is linked against my custom static library, c.lib, which uses Win32 API defined in w.dll. w.dll is located in C:\Windows\System32 and its import library is w.lib, located in Windows SDK directory. Shell w.lib be listed as Additional Dependency in c.lib or e.exe project? (e.exe builds successfully in both cases.) ... | I think you're misunderstanding what creating an archive and an import archive does.
Creating an archive, as you've rightly surmised in comments, creates a unified file containing compiled .objs. Now, this can contain any code you like, including but not limited to dynamic calls to libraries. An import library is a lib... |
4,647,046 | 4,688,884 | stringstream.good() > Different behaviour in VS and Eclipse compiler | I have some understanding problems regarding the stringstream.
Example:
stringstream stream(commands);
while (true) {
string line;
getline(stream, line);
if (!stream.good())
break;
if (line.size() > 0){
lines.push_back(line);
}
else{
... | To close this Question:
Like etarion said it's just a matter of the good() method. Using some other mechanism works fine.
Thanks for your help!
|
4,647,096 | 4,647,124 | Understanding C++ dynamic allocation | Consider the following code:
class CString
{
private:
char* buff;
size_t len;
public:
CString(const char* p):len(0), buff(nullptr)
{
cout << "Constructor called!"<<endl;
if (p!=nullptr)
{
len= strlen(p);
if (len>0)
{
buff= new ... | The addition function should return a CString, not a CString&. In the addition function, you should construct the return value, then delete[] temp as it is no longer needed, since inside the CString class you make a memory copy.
CString operator + (const CString& rhs) const
{
cout << "Addition operator called!"<<en... |
4,647,146 | 4,647,198 | Reverse a character array |
Possible Duplicate:
C++ Reverse Array
How can I reverse a character array? Like this:
char word1[10] = "this";
char word2[10] = word1[10] // in reverse
cout<<word2; // I want it to output "siht"
| How about a simple loop (since i do not know the exact type of word1 and word2)?
for (int i = 0, k = 9; i < 10; i++, k--) {
word2[k] = word1[i];
}
I highly suggest that you use std::string instead of char. There are plenty of answers on how to do this with std::string here.
|
4,647,254 | 4,648,203 | Several Services exporting the same COM component | According to this article:
http://msdn.microsoft.com/en-us/library/ms809975.aspx
you can export a component in a service.
But is it possible to create several services that export different instance of the same component?
I see one potential issue is when defining the \HKEY_CLASSES_ROOT\AppID\\LocalService, since each ... | It is quite explicitly mentioned in the linked article:
Do not use REGCLS_SINGLEUSE.
Registration fails if you use this
flag. The operating system allows a
single instance of a service. For this
reason, the COM component must be
available to multiple clients
simultaneously.
You have to use a regular out-o... |
4,647,577 | 4,647,644 | φ(n) = (p-1)(q-1) p and q are two big numbers find e such that gcd(e,φ(n)) = 1 | φ(n) = (p-1)(q-1)
p and q are two big numbers
find e such that gcd(e,φ(n)) = 1
consider p and q to be a very large prime number (Bigint). I want to find a efficient solution for this.
[Edit] I can solve this using a brute force method. But as the numbers are too big I need more efficient solution.
also 1< e < (p-1)(q... | Usually you choose e to be a prime number. A common choice is 65537. You then select p and q so that gcd(p-1, e)=1 and gcd(q-1, e)=1, which just required you to check that p-1 and q-1 are not multiples of e (when you (rarely) find that one of them is, you generate a new prime instead).
65537 has the advantage of allowi... |
4,647,791 | 4,650,195 | Using LibTiff in Visual Studio 2010 | I'm trying to use LibTiff in a C++ Program in Visual Studio 2010. I downloaded tiff-3.9.2.zip from ftp://ftp.remotesensing.org/pub/libtiff. To test LibTiff it would be nice if someone could give me a step by step instruction how to import libtiff to visual Studio and build the Fax2Tiff tool.
There are so many files so ... | I think it would be better
to build libtiff as a static library.
to build fax2tiff as a console application that links with the library
In addition, you should decide which version of the file- and memory-related files you want to use in your version of the library. There are Unix, DOS and Windows-style versions for ... |
4,647,875 | 4,648,850 | Get result type of function | I want to specialize a template function declared as:
template<typename Type> Type read(std::istream& is);
I then have a lot of static implementations
static int read_integer(std::istream& is);
a.s.o. Now I'd like to do a macro so that specialization of read is as simple as:
SPECIALIZE_READ(read_integer)
So I figure... | To my knowledge, there is no mechanism (other than decltype in C++0x) to obtain the return type from a function pointer, without passing that same function pointer as a parameter.
The easiest way is to accept the duplication of the return types:
#define SPECIALIZE_READ(type, read_function) \
template<> type read(std... |
4,647,941 | 4,648,707 | Specialization and template template parameters | I've the following:
template <template <typename, typename> class C, class T, class A >
class TTCTest
{
public:
TTCTest(C<T, A> parameter) { /* ... some stuff... */ }
C<T, A> _collection;
};
I want to ensure that the template is only instantiated where the T and A classes are of a specific type (path a... | You can do that with partial specialisation, where you fail to provide an implementation for the non-specialised case.
For example:
template <template <typename, typename> class C, class T, class A >
class TTCTest;
template <template <typename, typename> class C>
class TTCTest<C, path, allocator<path> >
{
// ...
};
... |
4,648,070 | 4,648,102 | static_cast vs dynamic_cast | Suppose I'm given a C++ library full of inheritance. I'm given a Base* in a function when I know that it is actually pointing to a Derived object and Derived inherits Base. But I don't know what kind of inheritance it is (public/protected/private). I also don't know if there is any virtual function in the hierarchy.
Gi... | Use static_cast. If you know that your Base* points to a Derived, then use static_cast. dynamic_cast is useful for when it might point to a derived.
|
4,648,483 | 4,648,560 | Will this cause a problem with different runtimes with DLL? | My gui application supports polymorphic timed events so that means that the user calls new, and the gui calls delete. This can create a problem if the runtimes are incompatible.
So I was told a proposed solution would be this:
class base;
class Deallocator {
void operator()(base* ptr)
{
delete ptr;
... | I suggest that you study the COM reference-counting paradigm (AddRef and Release). This allows more flexible lifetime and guarantees that the correct deallocator is used, because the object deletes itself.
Please note that if you're sharing class objects across DLL boundaries, you could have much bigger problems that ... |
4,648,597 | 4,648,627 | how to use string in va_start? | for some reason, i cant get this working:
void examplefunctionname(string str, ...){
...
va_start(ap, str.c_str());
nor do i get this work:
void examplefunctionname(string str, ...){
...
int len = str.length();
char *strlol = new char[len+1];
for(int i = 0; i < len; i++){
strlol[i] = st... | From the documentation:
va_start(va_list ap, last) ... The parameter last is the name of the last parameter before the variable argument list, i.e., the last parameter of which the calling function knows the type.
You've done this correctly in your working example: va_start(ap, str), and str is the last known argume... |
4,648,821 | 4,648,923 | Loop without consuming too many CPU cycles and without sleep()? | I am doing a VoIP program which continously checks whether the audio-recording buffer has anything in it (FMOD library, whenever the function getRecordPosition > 0, then the buffer has data in it).
So it would be something along the lines of:
while (true) {
if(getRecordPosition>0) {
process data....
}
}
... | The best thing to do, if you can, is to not emulate an event-driven architecture as you say, but to actually use an event-driven architecture. I don't know anything about your code, in particular whether you're in control of the audio-recording buffer's code or not. But if you do control the code that writes to the b... |
4,648,848 | 4,648,902 | std::set<std::pair<size_t, std::string> >::find(), without a string copy construction | I have an std::set of std::pairs, and the second pair is a string. I want to check if a pair exists in the set.
std::set< std::pair<size_t, std::string> > set_;
bool exists(size_t x, const std::string& s)
{
std::set< std::pair<size_t, std::string> >::iterator i = set_.find(std::make_pair(x, s)); // copy of s is c... | Use pointer to string and override predicate less (see constructor of std::set)
|
4,648,878 | 4,648,900 | Is it possible to return an iterator as an index? | For example, if I use std::find_if like this:
std::vector<Rect>::iterator it =
std::find_if(regions.begin(), regions.end(), find_region(x,y));
Can I get the index of the iterator it in a straightforward way?
| Try std::distance(regions.begin(), it) from the <iterator> header file.
|
4,648,893 | 4,649,633 | how to reset a large number of class members at once, not in a destructor? | I have a class containing many members of a simple class type. More importantly, their number is growing as I go on with the development.
I need to be able to reset them all at once, and I'd like to do it without copy-pasting them. The code currently looks like:
typedef auto_ptr<odbc::PreparedStatement> Stmt;
class D... | There's no need for the extra auto_ptr (each Stmt being an auto_ptr anyway), if you collect them in a single class you can reset them with a simple assignment. Unlike an array solution you still preserve their meaningful names.
Note that you can't use an unnamed temporary (e.g. stmts = OdbcResources();) as the generate... |
4,648,948 | 4,648,994 | Request for member X of Y which is of non-class type Z | When trying to compile the following snippet of C++ code (complete source below)
A::A(istream& i) {
vector<string> words( istream_iterator<int>(i), istream_iterator<int> );
words.begin();
}
I'm getting the error
istream_it.cpp:12: error: request for member ‘begin’ in ‘words’, which is of non-class type
‘std:... | Correct,
vector<int> words(istream_iterator<int>(i), istream_iterator<int> );
this is a function named words taking two istream_iterator<int> parameters, one of which named i and the other has no name, and returning vector. Change to this:
vector<int> words((istream_iterator<int>(i)), istream_iterator<int>() );
The ... |
4,649,129 | 4,649,165 | Difference between these two functions that find Palindromes | I wrote a function to check whether a word is palindrome or not but "unexpectedly", that function failed quite badly, here it is:
bool isPalindrome (const string& s){
string reverse = "";
string original = s;
for (string_sz i = 0; i != original.size(); ++i){
reverse += original.back();
original.pop_back();
}
... | for (string_sz i = 0; i != original.size(); ++i) {
reverse += original.back();
original.pop_back();
}
original.size() changes as you pop elements off the back. Effectively, you keep incrementing i and decrementing original.size(); they may never be equal.
if (reverse == original)
This will never be true sinc... |
4,649,178 | 4,649,210 | Visual Studio 2010 compile error with std::string? | So this is possibly the strangest thing I've seen recently and was curious how this could happen. The compiler gave me an error saying that std::string is undefined when used as a return type but not when used as a parameter in methods of a class!
#pragma once
#include <string>
#include <vector>
// forward declaratio... | This is probably a compiler bug. I have seen several others in VS2010.
|
4,649,231 | 4,649,301 | if (mask & VALUE) or if ((mask & VALUE) == VALUE)? | You're probably familiar with the enum bitmask scheme, like:
enum Flags {
FLAG1 = 0x1,
FLAG2 = 0x2,
FLAG3 = 0x4,
FLAG4 = 0x8,
NO_FLAGS = 0,
ALL_FLAGS = FLAG1 | FLAG2 | FLAG3 | FLAG4
};
f(FLAG2 | FLAG4);
I've seen a lot of code that then tests for a certain bit in the mask like
if ((mask & FLA... | The construct if ((mask & FLAG3) == FLAG3) tests if all bits in FLAG3 are present in mask; if (mask & FLAG3) tests if any are present.
If you know FLAG3 has exactly 1 bit set, they are equivalent, but if you are potentially defining compound conditions, it can be clearer to get into the habit of explicitly testing for ... |
4,649,363 | 4,649,470 | Visual Studio expression containing a term named "by" cannot be evaluated in the watch window | Consider my C++ code below:
int _tmain(int argc, _TCHAR* argv[])
{
int by = 10;
printf("%d\n", by);
int bx = 20;
printf("%d\n", (by + bx));
return 0;
}
which works fine. The funny thing is with the "by" variable. If I try to add a watch for a simple expression that contains by, the result will be... | What you're seeing here is the C++ Expression Evaluator's implementation of the BY operator. Your use of the expression BY is being interpreted as an operator instead of a local variable.
Reference: http://msdn.microsoft.com/en-us/library/56638b75.aspx
A lot of discussion has gone into whether or not this behavior i... |
4,649,388 | 4,649,507 | What is the native narrow string encoding on Windows? | The Subversion API has a number of functions for converting from "natively-encoded" strings to strings that are encoded in UTF-8. My question is: what is this native encoding on Windows? Does it depend on locale?
| "Natively encoded" strings are strings written in whatever code page the user is using. That is, they are numbers that are translated to the appropriate glyphs based on the correct code page. Assuming the file was saved that way and not as a UTF-8 file.
This is a candidate question for Joel's article on Unicode.
Specif... |
4,649,513 | 4,650,041 | Is it possible to pass a reference to a pointer from Excel VBA to C++? | I would like to call my own C++ dll function from excel vba:
void my_cpp_fun ( int& n_size, double*& my_array);
The C++ function creates an array my_array of variable size n_size (this size is computed within my_cpp_fun).
Can I interface this function as is to VBA without using any Excel specific stuff in my C++ code?... | Short answer: yes, it is possible (and easier than the COM route, in my opinion) to call functions in a DLL from VBA. In my experience, the best way to go is to write wrapper functions with C linkage (to avoid running into various C++ name-mangling schemes) and exposing an interface of pointers rather than references (... |
4,649,554 | 4,653,190 | Rounding differences on Windows vs Unix based system in sprintf | I have problem on UNIX based systems sprintf does not round up properly value.
For example
double tmp = 88888888888885.875
char out[512];
Thats 88,888,888,888,885.875 just to be easier on eyes.
I am giving such specific and big example because it seems it works fine on smaller numbers.
I am trying to use it in followi... | There is a bug report for glibc with a problem very similar to yours. The main conclusion (in comment 46) here is that double is not a 15-decimal-digit number and you should not expect it to work like that.
As a workaround you can add something small to your numbers to make them round better. But this solution is not g... |
4,649,734 | 4,649,844 | What reasons are there to place member functions before member variables or vice/versa? | Given a class, what reasoning is there for either of the two following code styles?
Style A:
class Foo {
private:
doWork();
int bar;
}
Style B:
class Foo {
private:
int bar;
doWork();
}
For me, they are a tie. I like Style A because the member variables feel more fine-graine... | In C++, it is common for those using the class to look at the definition in code, in the header file.
In Java, it is common (but not universal) for those using the class to look at documentation generated from JavaDoc comments. IDEs support style B.
Therefore:
In C++ I use style A, placing the public interface at the... |
4,649,739 | 4,649,828 | When exactly would a DLL use a different heap than the executable? | I know that if your DLL static links against a different version of the runtime then it creates its own heap. It will also if it is instructed to make a heap. Under these circumstances, it is unsafe for the DLL to delete what the exe allocated. In what cases does this NOT apply (as in, it is safe for the DLL to delete... | I may be reading more into your question than is there, but if you are wanting to know how you can allocate and free memory across DLL boundaries, then you might use something like the following:
#define DLLMemAlloc( size ) HeapAlloc( GetProcessHeap(), 0, size )
#define DLLMemFree( mem ) HeapFree( GetProcessHeap(), 0... |
4,649,793 | 4,649,975 | C++ Multi threaded directory scan code | I was looking how to write a multi threaded C++ code for scanning directory and get list of all files underneath. I have written a single threaded code which can do and below the code which can do that.
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>... | boost::filesystem has directory_iterator and recursive_directory_iterator, the former will get all the contents of a directory but not recurse sub-directories, the latter will also recurse subdirectories.
With regard to thread-safety, you could lock a mutex then copy the results into a std::vector or two vector instan... |
4,649,801 | 4,649,924 | Organizing GLSL shaders in OpenGL engine | Which is better ?
To have one shader program with a lot of uniforms specifying
lights to use, or mappings to do (e.g. I need one mesh to be parallax mapped, and another one parallax/specular mapped). I'd make a cached list of uniforms for lazy transfers, and just change a couple of uniforms for every next mesh if it ... | Most modern engines I know have a "shader cache" and use the second option, because apparently it's faster.
Also you can take a look at the ARB_shader_subroutine which allows dynamic linkage. But I think it's only available on DX11 class hardware.
|
4,649,817 | 4,650,657 | Map existing C++ function to JNI | I have a library that I am compiling and creating a fully standalone C++ program. There are two cpp files, one that has the main, the other with all the functionality.
Currently, this program is implemented with a Java ProcessBuilder with args to call the C++ program and the results of that C++ program just simply go o... | Java Native Access (JNA) will do what you want.
Java Native Interface (JNI) requires an additional layer of C glue between Java and C++. But JNA can access some C functions directly from Java.
You'll probably need to declare your function extern "C". You won't have to recompile the library, but you will have to link ... |
4,650,003 | 4,652,197 | Reduce ranges of doubles in C++ | I've seen various approaches in other languages for how to do this, but it seems like a common enough problem that it seems like there should be a standard way to do this.
I want to collapse a list of float ranges to its smallest representation.
2.45-3.72
3.16-6.55
7.23-8.96
8.95-10.27
would become:
2.45-6.55
7.23-10.2... | Sound simple:
start with list of ranges
let current = first range in the list
while there's a next range after current:
if next overlaps current:
extend current to also contain next
remove next from the list
else:
advance current one forward
That should do the trick.
|
4,650,194 | 4,650,621 | c++ Problem with timer counter being shared between multiple instances of a class | I have a simple timer class in a game, intended to allow me to make an entity do something every so many seconds. It has two functions:
void Timer::GameTimer() // Gets time between frames
{
::ElapsedTime = Clock.GetElapsedTime();
Clock.Reset();
}
This just updates the ElapsedTime Global so that it can be grabb... | static in this context means only one instance of something exists at a time and is initialized once.
The easiest fix to me would be to (not necessarily the best fix):
- Remove the static qualifier
- make ftime and n member variables of Timer
- Create an instance of Timer for each entity that you want to react... |
4,650,243 | 4,650,280 | Convert Python program to C/C++ code? | is it possible to convert a Python program to C/C++?
I need to implement a couple of algorithms, and I'm not sure if the performance gap is big enough to justify all the pain I'd go through when doing it in C/C++ (which I'm not good at). I thought about writing one simple algorithm and benchmark it against such a conve... | Yes. Look at Cython. It does just that: Converts Python to C for speedups.
|
4,650,340 | 4,650,356 | * is c++ function name? | While browsing the Genode source code documentation, I came across a function who's name started with an asterisk (*), specifically,
Hello::Session_component *_create_session(const char *args)
I typically work in C, not C++ so am a little confused by this. Is this a pointer to a function named _create_session(), is th... | The function is named _create_session, and its return type is a pointer to a Hello::Session_component.
This works just as it does in C:
T *func(); // return type is T*
T* func(); // exact same declaration
|
4,650,376 | 4,650,470 | Derived destructor called before base destructor causes issue | Here is my issue:
My base class has a constructor that takes in a class pointer, if that pointer is NULL, it knows to instance it itself and maintain it.
The problem is, in the base destructor, I have to unregister that pointer with something private of base. So what happens is when I try to make a call to the class po... | If the base class creates an instance for the pointer, why can't it free it as well? Is there anything stopping you from moving the free into the base destructor?
It's always best to be consistent in terms of who does what, at a certain level of hierarchy- splitting up the same responsibility across several levels of h... |
4,650,583 | 4,650,640 | Error using boost::function 1.44 in Visual Studio 2010 | I tried a simple example with boost::function. However I got the compiler error said:
#include <boost/array.hpp>
#include <boost/function.hpp>
#include <iostream>
float div( float x, float y ) {
return x / y;
}
int main() {
boost::function<float (float x, float y)> f;
f = ÷
std::cout << f( 3.0f, 3.5f ) << "\n... | What follows the error is actually quite interesting :
1> e:[...]\main.cpp(11): error C2568: '=' : unable to resolve function overload
1> e:[...]\main.cpp(5): could be 'float div(float,float)'
1> d:\microsoft visual studio 10.0\vc\include\stdlib.h(479): or 'lldiv_t div(_int64,_int64)'
1> ... |
4,650,620 | 4,650,665 | Construction from Array | I'm developing a simple container class for C++ and I realized it would be helpful to be able to copy values from an array.
It's the difference between this:
myClass myInstance;
myInstance += 2;
myInstance += 4;
myInstance += 8;
myInstance += 16;
And this:
myClass myInstance;
int myArray[] = {2, 4, 8, 16};
myInstance ... | Actually, you can accept native arrays by reference. Here is an example of assignment operator that does what you want:
template <std::size_t N>
const myClass& operator=(const int(&arr)[N])
{
// use arr as you do usually with arrays :)
// N is the size of the array.
return *this;
}
|
4,650,846 | 4,650,884 | Is it possible to avoid namespace boilerplate in a header file? | I have some helper classes that I don't want in the global namespace, so I want to put them in their own namespace. For example:
// Widget.h
namespace MyHelpers {
class Helper { ... };
}
class Foo {
void bar(MyHelpers::Helper *helper);
}
// Widget.cpp
using namespace MyHelpers;
Foo::bar(Helper *helper) { ..... | If you have many of these, create a type shortcut inside the using class declaration:
class Foo {
...
typedef MyHelpers::Helper Helper;
...
void bar(Helper *helper);
...
};
|
4,650,896 | 4,651,017 | How to minimize the memory usage of a struct-type? | for the transposition table (generally a hash table) of a Connect Four
game, I would like to use the memory efficiently (to store the most possible
number of elements). One table element has to store following information:
lock: unsigned 64 bit
move: [0..6] --> unsigned 3 bit
score: [-2000..2000] --> signed 12 bit
... | Depending on how you implement locks, it may be possible to reduce the size of your lock field (I'm assuming this is a typical SMP lock SMP machine)
One option would be to reduce the number of locks. That is, have a seperate, smaller array of locks, and lock an element derived from your array element here. That is, if ... |
4,650,911 | 4,650,941 | return 2d array from function in C++ | I have a function declared like so:
unsigned char** Classifier::classify(){
//...
unsigned char **chars = new unsigned char *[H];
for(int i = 0; i < H; i++)
chars[i] = new unsigned char[W*3];
//...
return &chars;
//note: when this is "return chars;" I get the following: cannot convert ‘unsigned char*’ ... | This is never okay to ignore. You're returning the address of a local variable. That address will become invalid when you leave classify()'s stack frame, before the caller has a chance to use it.
You only need to return the value of that variable instead:
return chars;
|
4,650,998 | 4,651,351 | Linux c++: apis vs /proc files? | Im working on an app to collect and send various bits of system info (partition space/free, laptop battery info, etc). Im not having much success getting this information in the form of direct c++ api.. though its all available via files in /proc (or similar).
So - I'm wondering whether reading/parsing these files in m... | It is best practice by far to stick with an API in the following order of precedence.
Your language API (not much help for you here, but say for strings, a C99 string function is better to use than a library string facility specified by a Posix or other OS standard.)
Posix operating software APIs
Documented kernel API... |
4,651,041 | 4,671,107 | TMG SF_NOTIFY_POLICY_CHECK_COMPLETED Event | According to http://msdn.microsoft.com/en-us/library/ff823993%28v=VS.85%29.aspx, during this event the web filter can request GUID of the matching rule. I am assuming that is done by performing a GetServerVariable with type of SELECTED_RULE_GUID, since I could find no other readily identifiable means of doing so.
My pr... | After more investigation and testing, the GUID is accessible via the PersistentName of the FPCPolicyRule object. Since FPCPolicyRules->Item member only works on either Name or Index, I had to iterate through its items comparing each PersistentName against the GUID.
Apologies if this was obvious, took me a good day to w... |
4,651,249 | 4,651,263 | how to convert C# to C++ | Could someone please help me to convert C# to C++? here is an example:
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
namespace read_website
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Do... |
Actually as it is complicated to mix C# and C++ on unix, I am trying to convert C# to C++
Have you considered Mono? It is something that's definitely worth checking before starting to learn C++ in order convert and run an existing .NET application on Unix. It's also binary compatible meaning that you don't even need ... |
4,651,463 | 4,651,525 | Difference between C++0x lambdas and operator(), closure and functor | I'm confident I get the general gist of the constructs, but I can't see the purpose of them in c++. I have read the previous posts on the topic here on SO and elsewhere, but I fail to see why they should be a new language feature.
The things I would like answered is thusly
What is the difference between a lambda and a... | Lambdas are really just syntactic sugar for a functor. You could do it all yourself: defining a new class, making member variables to hold the captured values and references, hooking them up in the constructor, writing operator()(), and finally creating an instance and passing it. Or you could use a lambda that's 1/1... |
4,651,474 | 4,652,139 | How can I build variants of an executable with one makefile? |
I have one set of source files from which I need to generate multiple variants of an executable. For example I need to generate app1.elf, app2.elf, app3.elf from the same main.c and comm.c. The difference between each of the apps is a node address, a parameter that is passed down in the invocation of gcc. i.e.:
gcc -... | This is what I would do:
SRC = src/main.c
OBJ = $(patsubst src%,obj$(VERSION)%,$(patsubst %.c,%.o,$(SRC)))
C_FLAGS = -DNODE=$(VERSION)
all: app.1 app.2 app.3
#
# For each application just call make with VERSION set correctly
app.%: dir.%
$(MAKE) VERSION=$* app$*.elf
#
# Build each applications ... |
4,651,803 | 4,651,858 | Loading a library dynamically in Linux or OSX? | I know in Windows you would do something like LoadLibrary and then set your function pointer with GetProcAddress,
But how would something similar be done in Linux or OSX? The reason being is that I want to develop a plug in system for my X platform application.
Thanks
| You can use dlopen and friends on both Linux and Mac OS X (this Mac man page should work for both). Note, however, that you need to be careful not to mix 32-bit and 64-bit code and libraries; on the Mac, just make sure that the libraries are "universal binaries."
|
4,651,831 | 4,651,976 | Need to write a daemon in linux, not sure what to use C++ or C | I have a little problem picking the right language to write my daemon,
I am confused between C and C++, I want to use C++ because it is more expanded than C,
but I want to use C because it is the starting point of everything in linux,
I want to go for C++ as I have many resources about it, so, does it make any differen... | I can answer this one entirely in code. Writing a daemon roughly consists of doing this:
/*
* Daemon Initialisation:
* 1. Fork()
* 2. setsid()
* 3. Fork() do we need to do this twice?
* 4. Chdir /
* 5. Umask(0)
* 6. Close STDIN/OUT/ERR
* 7. Optionally re-open stuff.
*
* Refs:
* 1. http://www.faqs.org/faqs/un... |
4,651,869 | 4,651,924 | Given a COM DLL, extract all classes CLSID and corresponding interface name | My question is similar to Getting CLSID for a DLL file?, I think.
I have a directory with some DLLs, each one implementing one or more COM interfaces. I would like to get:
1) Each interface name
2) The CLSID of the class implementing the interface
For each DLL. It's important that everything can be done programatically... | You can't get that from the COM DLL, but you can get it from the typelib. I'm pretty sure the MIDL compiler has a switch to decompile a typelib, but parsing IDL wouldn't be as easy as using the TypeLib API.
To complicate matters, the typelib is often stored as a resource inside the DLL. So you'd extract the resource,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.