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 |
|---|---|---|---|---|
5,387,147 | 5,387,216 | Create folders on a remote Windows PC using C++? | How can I create folders on a remote Windows PC using C++?
| Directly, you can't -- there would have to be a service on the remote machine which exposes that functionality for you.
If you're talking about a server message block scenario (i.e. "Windows Filesharing"), you can just call CreateDirectory with a network path, i.e. "\\\\computername\\share\\newFolder", but this require... |
5,387,276 | 5,388,090 | Avoiding memory leaks | How can we use an overloaded operator to prevent memory leaks in C++?
Any complete example..
Regards,
PKV
| If you want to avoid memory leaks, don't use delete.
It may seem paradoxical, but the truth is that manual memory management is error prone, it is best to use automatic (or library) technics.
In C++, for each object that you create, there should be a clear ownership. That is, you should be able to identify the object l... |
5,387,324 | 5,390,100 | Auto pilot mode of application | Hey Guys I am working on Gateway Simulator.
here gateway simulator is connected with the camera.gateway respond when user sends command.
command can be like streaming video or status of the sensor associated battery information etc.There is data center also which will forward the user request to gateway.
There some in... | It depends on how (network, console, GUI, ...) the user is sending commands. If it's network or console, writing a script that will feed the command should not be too hard in any language, but there is a tool called expect, built on top of tcl, that's specifically designed for this task. Alternatively if you know perl ... |
5,387,412 | 5,387,911 | can any one explain the difference | n3035 says: (2010-02-16)
A variable is introduced by the declaration of an object. The variable's
name denotes the object.
n3090 says: (2010-03-29)
A variable is introduced by the declaration of a reference other than a
non-static data member or of an object. The variable's name denotes the
refe... | Consider:
int x = 42;
int& rx = x;
x is a variable; should rx also be considered a variable? Many of the Standard's requirements about non-reference variables also apply to references. It's obviously a pain to have to stipulate "variables or references to variables" constantly throughout the Standard, so if the defi... |
5,387,415 | 5,387,454 | Accessing non-const members in list of objects | I would like to access members of objects contained in a list of such objects.
I have a class CApp with a member std::list<Particle> PList serving as a list of particles.
A class Particle has a member void Update() which from my understanding of const can't be const because it affects the instance (euler integration an... | By using const_iterator you say that you don't want to change list elements.
If you want to, use std::list::iterator.
|
5,387,466 | 5,387,489 | Help needed in Use of Function pointer in C++ | i have made a sample example, in this i'm trying to pass a function as argument i am getting error, could you please help me
typedef void (*callbackptr)(int,int);
class Myfirst
{
public:
Myfirst();
~Myfirst();
void add(int i,callbackptr ptr)
{
ptr(i,3);
}
};
class Mysec
{
public:
Myf... | The type of the callback function you're passing as parameter is not defined as part of a class. You probably should define Testing as static.
|
5,387,664 | 5,387,772 | Deleting a Triple Pointer in c++ | I have a triple pointer to an Object in C++ and I need to free the entire thing after use.
MyClass *** foobar = new MyClass **[10000];
How do I write the delete statement for this.
| It depends on how you allocate the pointers-to-pointers. If you do:
int x;
int* p = &x;
int** pp = &p;
int*** ppp = &pp;
Then you don't have to delete anything.
On the other hand, if you do:
int* p = new int;
int** pp = &p;
int*** ppp = &pp;
Then you only have to delete p. For:
// i.e., allocate 1000 ints, return a... |
5,387,697 | 5,387,747 | Make select based loop as responsive as possible | This thread will be very responsive to network activity but can be guaranteed to process the message queue only as often as 100 times a second. I can keep reducing the timeout but after a certain point I will be busy-waiting and chewing up CPU. Is it true that this solution is about as good as I'll get without switchin... | It depends on what your OS provides for your. On Windows you can wait for a thread message and a bunch of handles simultaneously using MsgWaitForMultipleObjectsEx. This solves your problem. On other OS you should have something similar.
|
5,387,825 | 5,406,852 | Are there real life cases when C4930 Visual C++ warning doesn't indicate an error? | Visual C++ can emit C4930 "unused function prototype" warning in the following case:
void SomeUsefulFunction()
{
SomeResourceLock lock(); //C4930 - unused function prototype
//code requiring the above lock
}
in the above code the intention was to construct a stack-allocated RAII object:
void SomeUsefulFunction... | C++ makes it legal to make function-local declarations, although I've rarely seen this feature used. It's often an error, but for instance, if you really used such a declaration and called the matching function:
int main()
{
int foo();
return foo();
}
And then later removed the function call:
int main()
{
... |
5,388,087 | 5,388,267 | How to merge images? | I want to merge two different images.
Is there some library to do it ?
(.net platform or in unmanaged code (C++))
| You can use AlphaBlend function see here and here
|
5,388,097 | 5,423,373 | What's the c++ inline class? | I accidentally found that the Clang compiler allows :
inline class AAA
{
};
in C++.
What's this?
PS. I reported this to Clang mailing list cfe-dev@cs.uiuc.edu, and now waiting for reply. I'll update this question by I'm informed.
| I got an answer from Clang mailing list. It was a bug:
http://llvm.org/bugs/show_bug.cgi?id=3941
However it looks already been fixed in recent build.
Thanks anyway :)
Here's the conversation:
http://lists.cs.uiuc.edu/pipermail/cfe-dev/2011-March/014207.html
|
5,388,227 | 5,388,279 | How may integers should I allow in my container class? | I don't want the class to cause a crash due to too many values. I realize that it would take 268,435,456 integers (if I did my math correctly) to take up one gigabyte (which is pretty extreme). This value is merely an eighth of a signed integer's maximum value (which is what I am currently using for the length. Should ... | Placing arbitrary limits on your classes is considered bad practice.
You should allow the user to put as many items as they want into your container; if they try to put too many in, it's their job to deal with the std::bad_alloc exception that will be thrown.
|
5,388,373 | 5,388,395 | Delete an array of queue objects | I am working on an object that contains an array of queues with an array length that isn't decided until the constructor is called. Basically it looks something like the following
#include <queue>
class myClass{
public:
//public functions
private:
//private functions and variables
queue<int>* myQueue;
};
it is... | Because you allocated using new[] you should do delete[] myQueue; in destructor. Otherwise it would invoke undefined behavior. BTW, you can use std::vector<std::queue<int> > if you don't want to get this type of memory management issues.
|
5,388,412 | 5,388,449 | Create a statically typed variant in C++0x | I am wondering, if it's possible in C++0x to create a statically typed variant, (that behaves like auto) :
variant<int, bool, std::string> v = 45;
When we assign v to a value other than int, it doesn't compile:
v = true; //Compile error
So far I haven't found any elegant solution.
| This code compiles on my machine with Boost.Variant and g++ 4.5 for both C++98 and C++0x. Do you want to implement a variant-type yourself? Then you might look into the Boost implementation.
In the case that you want to /get/ the above behaviour you could do it like this:
auto v = 45;
static_assert(std::is_same<decltyp... |
5,388,493 | 5,388,632 | Reading specific bytes out of a byte array and converting them to hexadecimal representation, using Objective-C++ | I am trying to convert a GUID C++ structure into a string representation of the guid. The GUID structure is defined as follows:
typedef struct _GUID {
ul_u_long Data1;
ul_u_short Data2;
ul_u_short Data3;
ul_byte Data4[ 8 ];
} GUID;
I am having a problem with converting the Data4 to string. A description of th... | This snippet should work:
#include <cstdio>
#include <iostream>
GUID ulguid = {
0x6B29FC40u, 0xCA47, 0x1067,
{0xB3, 0x1D, 0x00, 0xDD, 0x01, 0x06, 0x62, 0xDA}
};
// 36 characters for the GUID, plus the zero terminator.
char buffer[37];
sprintf(buffer, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
ul... |
5,388,581 | 5,388,733 | How to lock a file for multiple computers in windows | (In c++)I want to make a process that will run on multiple computers that share the same file (on the same hard disk). And from each process I want to write to the end of a file, but only when no other process is using that file.
How can I lock that file when writing to it, or at least check if another process is using... | When you will try to open the file, it will fail if it is already being used.
To see if opening has failed, you can either :
Check ios::fail()
Call ios::exceptions() before opening the file,
|
5,388,667 | 5,395,991 | Do you ever NOT want to use virtual inheritance of a mutual base class if you use multiple is-a inheritance? | If you have is-a inheritance relationships implemented with public inheritance, and have a diamond of inheritance you will have something like:
a stream class
input stream and output stream classes derived from stream
an input/output stream class derived from both
In this case, as used in the standard library (?), to... | Let's work into a simple example.
B B1 B2
| \ /
D D
On the left, we find a class derived from a single bass. Clearly reasonable in OO design for having an is-a relationship respecting the Liskov Substitution Principal.
On the right, both B1 and B2 are independent bases of... |
5,388,925 | 5,388,975 | Java native library System.loadLibrary fails with UnsatisfiedLinkError | I'm trying to use a native C++ library in Java.
When I'm loading it with
System.loadLibrary(filename);
I get the error:
java.lang.UnsatisfiedLinkError:
Directory separator should not appear
in library name: C:\HelloWorld.dll
Any ideas how I can solve this?
| Just use:
System.loadLibrary("HelloWorld"); // without c:\ and without ".dll" extension
Also, make sure HelloWorld.dll is available on your library path.
|
5,389,153 | 5,389,198 | C++ API to get the private and virtual bytes consumed by a process | Is there an API provided by Microsoft to get the private and virtual bytes consumed by a process ?
| GetProcessMemoryInfo could be of great use.
|
5,389,180 | 5,389,220 | I can't understand why map cause segmentation fault | I have a loop that does the following:
short fooID;
char line[256]
map<short,foo> foos;
set<short> barIDs;
while (fgets(line,256,file) != NULL){
string line_copy = line;
/*use token to split the line into several parameters which does not effect foo * bar*/
string token = strtok(line,",");
token = strtok(NULL,"... | foo * bar;
This creates a variable bar pointing to a random location in memory. You need to make it point to a valid object: bar = new foo; - and remember to delete it when you're done, iterate over your map and delete all the foo's you added.
|
5,389,235 | 5,389,392 | How to overload operator ->* in C++ | Is there a way to overload ->* for use with a smart-pointer-like object? Below is what I would like to do. For simplicity I'm not using templates (I'll get to that once I have it working for a single fixed class). I can get it to work with pointers to data members, but I can't seem to get it right for pointers to mem... | Have a look at this article by Scott Meyers. It's quite old, but the only resource discussing overloading ->* that I know of.
Note that the standard library's iterator and smart pointer types don't overload ->*. I don't know the reasons, but I suspect it's because that operator rarely ever used, is a lot of hassle to ... |
5,389,304 | 5,389,484 | error: expected primary-expression before ‘.’ token | whats the problem of this code that i take the above error?
TIA
#include"PositionInfo.h"
bool DecisionTree::Decision(Agent & agent) {
PositionInfo Player_position;
double metr=Player_position.GetBallDistToTeammate(5);
if (agent.GetSelf().IsKickable()) {
Kicker::instance().KickBall(agent,agent.GetWorldState().GetTea... | PositionInfo is a class. GetBallDistToTeammate() is a method.
Given the name of the function and the number of arguments (one), I would suggest that a static method would not be be able to calculate a distance with that information.
As such you'd need to construct an instance of PositionInfo (let's call it player_posit... |
5,389,411 | 5,389,473 | Is this undefined behavior in C/C++ | int foo(int c){
return c;
}
int main(void){
int a=5,c;
c = foo(--a) + a;
}
Will it invoke undefined behavior in C/C++? I think no it won't.
After reading all the answers I can't figure out whether it is undefined behavior or unspecified behavior.
| Yes it's undefined behavior - a and foo(--a) can be evaluated in any order.
For further reference, see e.g. Sequence Point. There's a sequence point after the complete expression, and after evaluation of the argument to foo - but the order of evaluation of subexpressions is unspecified, per 5/4:
Except where noted, th... |
5,389,688 | 5,389,718 | What are the ways to delete objects in C++? | In unmanaged C++, how do I clear objects from memory?
| That depends how you allocated them:
new should be matched by delete
new[] should be matched by delete[]
malloc should be matched by free (you should never have to use this in C++ though)
Now, forget all these things, use Smart Pointers and read about RAII.
|
5,389,782 | 5,389,978 | How can Binder2nd objects that store pointers to member functions be used in a map? | My question is similar to this one. I need to store pointers to member functions in the map. The member functions takes an argument, which has to binded by a specific value while constructing the map. How do i do that? Should map have a binder2nd object as its value.
Eg:
enum { FOO, BAR };
exMap["foo"] = bind2nd(&cla... | Here is an example that works using Boost.Function:
#include "boost/function.hpp"
#include <map>
#include <iostream>
#include <functional>
struct Foo {
void bar(int x) {
std::cout << "bar called with x=" << x << std::endl;
}
};
int main()
{
Foo foo;
std::map<int, boost::function<void (Foo*)> >... |
5,389,951 | 5,389,982 | const pointer as class field assign | I'm back to C++ and little help is needed. I know what's const pointer, but I can find out, how to assign it in constructor properly That's frustrating ;)
so for example:
public:
TransferManager::TransferManager( Account * source, double amount )
{
account = source; // that doesn't work ;)
}
private:
Acc... | Use the initializer-list to initialize const members:
TransferManager::TransferManager( Account * source, double amount ) : account(source) {
}
The error message is saying that you're trying to assign to something that is const - that's not permitted. You have to initialize such member variables, not assign to them.
|
5,390,015 | 5,390,199 | How to limit the log size in c++? | In my application i am creating log file of size 5kb .If i exceeds 5 kb of file size , I have to overwrite the old contents with the help of new contents.
If you have any ideas just share with me.
I also need implementation of this technique in c++
I provide some example
Initially the file look like this
sample.txt
sam... | Here is some code I have recently written to implement a simple log-file rotation:
std::ostream & libLogging::FileRotationLogSink::GetCurrentStream(
std::string::size_type required )
{
if ( static_cast<std::string::size_type>(m_CurrentStream.tellp( )) +
required > m_Limit ) {
m_CurrentStream.c... |
5,390,081 | 5,717,624 | Make / gcc cryptic error 2: how to have more information? | I have this C++ project which compiles using a Makefile, and sometimes when (my guess) there are some missing includes, I get a cryptic "error 2" message and the make process stops.
I suspect the missing includes because this is the third times it happens when I included a non-existent header file.
It looks like this:
... | Ok my edit solved the problem: placing a dash - in front of include hides the error messages coming from the dependency generation.
Note for later: don't try to outsmart Make.
|
5,390,192 | 5,439,962 | Remove spaces and add newlines with astyle on c++ code | I inherited a massive amount of code formatted as follows:
void <whitespace> Foo::bar <whitespace> ( ) <whitespace> // short documentation
{
// code
}
void Foo::bar()
{
// code
}
with no empty line at the end of files and sometimes missing newline between functions. I've successfully used the following options wit... | I don't know what platform you're using, but if you're on any type of NIX-based platform, you have access to a lot of text-editing tools such as sed, meaning you don't have to roll your own code to do it.
I'm not great with regex, but the general syntax for sed search and replace on the command line is this:
sed -i -e ... |
5,390,224 | 5,390,903 | How to optimize my query in c++? | In My Application , I saved thousands of records in list of objects(i.e.,object array).I like to retrieve the data on the basis of particular scenario like date , name ., etc in record.
My idea is that in the for loop i am comparing the data with each record and retrive the record and send to the user.
but I felt that ... | Since you mentioned c also, you can implement sorted arrays of pointers if your list is static.
int num_records = number_of_records_in_array;
Record **Records_by_name = malloc(sizeof(Record *)*num_records);
Record **Records_by_date = malloc(sizeof(Record *)*num_records);
Then assign each pointer to a rec... |
5,390,260 | 5,418,259 | Referencing static object - alignment trap triggered on ARM proc | I have a class:
class A {
public:
static A& instance();
...
void setValue(int val){ _value = val; }
private:
int _value;
}
A& A::instance(){
static A _Instance;
return _Instance;
}
I am running this on an ARM processor. The issue I am encountering is that the application is triggering an alignment... | Thanks for the input guys. It turns out the root cause of this problem was a segmentation fault. The disassembly showed that the alignment trap pointed to the fault signal handler subroutine. I'm looking into why this happened now, but the question I originally asked is no longer relevant.
|
5,390,274 | 5,390,410 | Is this undefined behavior in C/C++ (Part 2) | What does the rule about sequence points say about the following code?
int main(void) {
int i = 5;
printf("%d", ++i, i); /* Statement 1 */
}
There is just one %d. I am confused because I am getting 6 as output in compilers GCC, Turbo C++ and Visual C++. Is the behavior well defined or what?
This is related to... | It's undefined because of 2 reasons:
The value of i is twice used without an intervening sequence point (the comma in argument lists is not the comma operator and does not introduce a sequence point).
You're calling a variadic function without a prototype in scope.
The number of arguments passed to printf() are not ... |
5,390,430 | 5,391,397 | Disable /W4 warnings for boost | How can I disable all MSVC warnings that come from the boost library?
I know I can disable specific warnings where they occur etc... but it clutters my code and if I use boost macros then they don't seem to work. I would like to have a simple way to tell my compiler to not give me warnings about boost. Is this possible... | They try extremely hard to avoid warnings, but some compilers warn for code that is formally correct, just a bit "suspicious". If you change the code to silence the warning, another compiler might warn for that code!
There is a warning policy for Boost code and various compilers
https://svn.boost.org/trac/boost/wiki/Gu... |
5,390,627 | 5,390,668 | Reading off the end of an array: running in terminal vs. debugger | I encountered an error in my code where an if() statement was checking a value off the end of an array. IE,
int arrayX [2];
if(arrayX [2])
FunctionCall();
This was leading to a function call that, for reasons related to the length of the above array, tried to subscript a vector with an out-of-bounds index, casuing... | Many debuggers fill unused memory with some distinct pattern, so that exactly the behaviour you describe happens.
|
5,390,649 | 5,404,260 | Create a proxy of QAbstractModelItem | I'm writing a Qt application to allow the visualization of very heavy data sets.
So, I have a SourceDataModel class, inheriting from QAbstractItemModel that seems to work properly (currently, I only display it in QTableView/QTreeView but later on, I'll create some custom views).
Now, I would like to be able to filter t... | The problem was that the view do not use QAbstractItemModel::data() from its model, but rather calls QModelIndex::data() on its items, which in turn calls the QAbstractItemModel::data() of the item's underlying model.
And since my proxy returned model indexes from the underlying model, that is why the SourceDataModel::... |
5,390,711 | 5,390,842 | How to remove duplicates from std::vector <std::pair<UnicodeString, UnicodeString> > | how to remove duplicate values from
std::vector <std::pair<UnicodeString, UnicodeString> > myVect;
Is there any built in function or i need to write a custom code for this
| Assuming that (a) a std::set is not what you want [that is you want to allow duplicate elements in your std::vector, only to remove them later] and (b) you don't wish to change the order of the elements in your std::vector [that is, the current order is important], which are both reasonable situations... You should be... |
5,390,791 | 5,390,862 | Linux C++ project directory layout - CMake | I would like to use some standard layout for my linux c++ project which is built using cmake and contains some executables and a library that these execs might link to. Currently I just had a folder for the project and a sub folder for each sub project. With a CMakeLists in the top level and one in each sub level that... | I wouldn't put the lib, bin and test output directly on the project directory: if you want to make a debug and a release build, you get stuck, because you have only one placeholder. Out of source build is your friend! I would use something like:
Project
src
include
CMakeLists.txt
These will be generated... |
5,390,883 | 5,390,981 | child timeout in fork execlp call | I have a programme where in the child ssh's into a server and executes a command and returns back. the parent handles the child by signal(SIGCHLD, SIG_IGN). Is there a way suchthat the child will timeout if the ssh server is not responding and an ssh from the commandline and waits for the other server forever?
| From ssh_config(5):
ConnectTimeout
Specifies the timeout (in seconds) used when
connecting to the SSH server, instead of using the
default system TCP timeout. This value is used only
when the target is down or really unreachable, not
when it refuses the connection.
You ca... |
5,391,207 | 5,391,346 | How to know that a triangle triple exists in our array? | I was stuck in solving the following interview practice question:
I have to write a function:
int triangle(int[] A);
that given a zero-indexed array A consisting of N integers returns 1 if there exists a triple (P, Q, R) such that 0 < P < Q < R < N.
A[P] + A[Q] > A[R],
A[Q] + A[R] > A[P],
A[R] + A[P] > A[Q].
The ... | First of all, you can sort your sequence. For the sorted sequence it's enough to check that A[i] + A[j] > A[k] for i < j < k, because A[i] + A[k] > A[k] > A[j] etc., so the other 2 inequalities are automatically true.
(From now on, i < j < k.)
Next, it's enough to check that A[i] + A[j] > A[j+1], because other A[k] are... |
5,391,322 | 5,391,670 | C Variadic function in a C++ wrapper | I am rewriting a C wrapper around a C Python API (Python 1.5) and I noticed that the function Py_VaBuildValue uses variadic number of args. I wondered if I have to use the same in my C++ function wrapper to pass to this function or if there is a more C++ way to deal with this?
I know variadic functions can be the caus... | If you want to be clever and don't fear some heavy template wizardry, it should be possible to generate (or massage) valfmt to always match the types you want to pass (I am assuming it uses format specifiers similar to printf, but the technique is applicable to any kind of format specification). You could do something ... |
5,391,927 | 5,392,085 | g++ 4.5 can't find a friend function | G'day!
I have a question around the use of friend in C++. Consider the following piece of code:
#include <ostream>
struct F {
};
struct N {
friend std::ostream& operator<< (std::ostream&, const N&);
friend std::ostream& operator<< (std::ostream&, const F&);
};
void foo(std::ostream &out) {
F bar;
out << ... | You have to declare the operators outside the struct as well. Same error is reported by gcc 4.4.
#include <ostream>
struct F {
};
struct N {
friend std::ostream& operator<< (std::ostream&, const N&);
friend std::ostream& operator<< (std::ostream&, const F&);
};
std::ostream& operator<< (std::ostream&, const ... |
5,391,973 | 5,392,050 | Undefined reference to static const int | I ran into an interesting issue today. Consider this simple example:
template <typename T>
void foo(const T & a) { /* code */ }
// This would also fail
// void foo(const int & a) { /* code */ }
class Bar
{
public:
static const int kConst = 1;
void func()
{
foo(kConst); // This is the importa... | It's intentional, 9.4.2/4 says:
If a static data member is of const integral or const enumeration type,
its declaration in the class
definition can specify a
constant-initializer which shall be an
integral constant expression (5.19) In
that case, the member can appear in
integral constant expressions. The
... |
5,392,124 | 5,392,310 | Scheduling Task in using C++ On linux and Windows machine | I am working on Gateway Simulator Application application.the gateway Streams the video to the client.Gateway Simulator can simulate the 1000 gateway.a user can issue the command like start the recording after 1 hour and record upto 1 hour or may be strem the video at 5'oclock.So basically scheduling the task.
This gat... | In QT, scheduling can be done with QTime and QTimer.
Simple: start a timer per scheduled event based on the difference between now and event-time
more scalable (1000 requests): maintain a container of events and start 1 timer to the first event.
|
5,392,517 | 5,402,543 | How to combine boost::exception with boost::unit_test and have a nice message | When I have the following auto test case :
class MyException: virtual public boost::exception,
virtual public std::exception
{
};
BOOST_AUTO_TEST_CASE(ExceptionTest)
{
BOOST_THROW_EXCEPTION(MyException());
}
Running the test gives:
ExceptionTest.cpp(14): fatal error in "void ExceptionTest::t... | I found how to do this:
Use a global fixture like so:
#include "boost/test/unit_test_monitor.hpp"
class Fixture
{
public:
Fixture();
~Fixture();
};
void translateBoostException(const boost::exception &e)
{
BOOST_FAIL(boost::diagnostic_information(e));
}
Fixture::Fixture()
{
boost::unit_te... |
5,392,897 | 5,392,934 | Console output - way to let caret jump to columns and rows | Is it possible to output such a escape code so that the caret in console moves to proper absolute location? I've seen something similar on unix console. Is this even possible on the basic and simple Windows console?
Thanks
| Don't use an escape code, use SetConsoleCursorPosition
COORD C = { 3, 3 };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), C);
|
5,392,996 | 5,393,143 | shared_ptr based design issues | I use shared_ptr in my application design, and I have tendency that more and more objects become heap-allocated instead of to be a simple objects on stack (or agregates of more complex objects).
Instead of simple (but with risk that Foo::bar will become dangling reference in more complex situation) ...
struct Bar { };... | It is a question of your object life cycle. You should use shared_ptr when you really share an object between multiple other objects.
In your case the owner of FOO and BAR must control the lifecycle of both. Maybe it is possible to make BAR a private member of you class FOO and let FOO control the life cycle.
I person... |
5,393,257 | 5,393,897 | Including R standalone library in a C++ source tree | I am working on a large open source C++ program that uses the R standalone library (libRmath, Ubuntu/Debian package r-mathlib). I want to remove this dependency: I'd like to include the source code from the R standalone library in my source tree, without the entire R source code. Can this be done?
Unfortunately, the R ... | A few points for you:
Can this be done? Of course it can, just copy and paste the code for r-mathlib into your project. The licensing for that library is a very liberal LGPL. Now, is it a good idea? I don't think so. Shared libraries have upside in that you get bugfixes, easier and shorter build etc/
Seems tightly c... |
5,393,293 | 5,393,333 | Undefined reference to 'Class::Class' | After fixing the previous problem (see my one other question that I have asked). I had declared more classes.
One of these is called CombatAdmin which does various things: (Header file)
#ifndef COMBATADMIN_H
#define COMBATADMIN_H
#include <string> // Need this line or it complains
#include <Player.h>
#include <Sound.h... | You have declared the default constructor (CombatAdmin()) and thus prevented the compiler from automatically generating it. Thus, you either need to 1) remove declaration of the default constructor from the class, or 2) provide an implementation.
|
5,393,699 | 5,393,742 | ActiveX in VC++ without MFC? | I'm wondering if it is possible to create an ActiveX control without using the MFC ActiveX that is provided in VS2010? I prefer to do the code entirely from scratch without any predefined or generated content. All the guides on ActiveX are based on using MFC and all the generated code is quite confusing and hard to get... | True, you don't need MFC (or any other framework) to develop ActiveX controls but there's a good reason you're not finding examples on how to do it without. It's incredibly tough to do so. My suggestion is to take the time to learn a framework that supports ActiveX and implement the ActiveX control. It will take you mu... |
5,393,997 | 5,394,095 | Stopping the debugger when a NaN floating point number is produced | I have an C++ program. Somewhere in the program (hard to reproduce, but reproduceable) a caclculation results in a float beeing set to a NaN. Since a floating point operation involving a NaN results in a NaN, this spreads fast.
Is there any way I can setup the compiler (gcc 4.4) or the debuger (gdb) to stop when a floa... | You could enable floating point exceptions - see glibc Control Functions - then you'll get a SIGFPE when your NaN value is produced
|
5,394,018 | 13,608,763 | Memory Allocation issue when modifying CreateToolbarEx function with new bitmap | I'm trying to modify some old code (c++) that uses the CreateToolbarEx function, in an attempt to use a new bitmap and replace our 24x24 pixel toolbar buttons with flashier 36x36 ones. The function I'm using is as follows:
m_hToolbarWnd = CreateToolbarEx(m_hPagerWnd, ws, ID_TOOLBAR, NUMBERTOOLBARBITMAPS, hInst, IDB_TO... | This is old, but hopefully the solution I found will help someone. I had overlooked the fact that I was changing from a 16-bit color bitmap to 24-bit, which I was unable to get CreateToolbarEx to handle. Instead, I had to call CreateWindowEx and create and set the icon ImageList for it. Working code:
m_hToolbarWnd =... |
5,394,146 | 5,397,102 | Make file header file dependency | I want to add header file dependency in make file
I written rule
${OBJECTDIR}/%.o: %.cc %.h
gcc $(WarningLevel) $(CFLAGS) $(INCLUDES) -c -o $@ $^
but there are two error
One for .cc file which don't have any .h files . It will give no rule to make.
Second one is the object file build by rule give error at l... | First of all, you haven't shown us your link command. Secondly, you shouldn't be using $^ here. $^ expands to a list of all dependencies (here, the .c and the .h), but we only want to compile the .c file. Use $<, which expands only to the name of the first dependency:
${OBJECTDIR}/%.o: %.c %.h
gcc $(WarningLeve... |
5,394,272 | 5,395,392 | Questions about Generic Error Handling in programming | I'm somewhat confused when talking about error handling.
Take Direct2D for example.
Before we can start using Direct2D functionality, we have to create a ID2DFactory object:
HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2d1Factory);
As you can see from above. We can check the HRESULT hr to see if... | Initialization functions like your D2D1CreateFactory() can fail. Such a failure generally means the O/S on your PC is completely hosed and you need to reboot. This information is valuable to the user, who would like to know "O/S is hosed, reboot and try again" versus "dereferenced nil at like 2345 in module mod.c". If ... |
5,394,342 | 5,394,414 | how to define a structure in a class? |
I have a class:
class systemcall
{
typedef struct
{
int pid;
int fptrCntr;
OpenFile openfileptrs[10];
}processTable[100];
public:
//other stuff...
}
I have a member function
/* this function initializes the process table. */
void systemcall::initpTable()
{
int... | You don't want the typedef before the declaration of processTable since you are declaring an object, not a type. After defining processTable as a type, you then proceed to use it as a member object, which confuses the compiler.
|
5,394,913 | 5,395,088 | QTimer stops and starts by itself | Here is how I use QTimer:
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->setInterval(1000);
timer->start();
Program monitors update() function and prints the current time in it. Normally it works as expected, it prints time at every second, but when program starts to... | QTimer (and all event-base message deliveries) is not interrupt driven. That means you are not guaranteed you will receive the event right when it's sent. The accuracy describes how the event is triggered, not how it's delivered.
If you are not doing threaded process on long job, call QCoreApplication::processEvents() ... |
5,395,001 | 5,395,199 | Template filled by an operator | Can you use templates (or the like) in C++ to specify which operation is done in a function?
I don't know how to explain it more clearly, so I'll show you how it could be (but isn't) done in code:
template <operator OPERATION> int getMaxOrMin(int a, int b) {
return a OPERATION b ? a : b;
}
where finding the maximu... | Yes but you need to define it like a functor:
template <typename OPERATION>
int getMaxOrMin(int a, int b)
{
OPERATION operation;
return operation(a, b) ? a : b;
}
Now you can use it like this:
struct myLess
{
bool operator()(int a,int b) const { return a < b; }
}
struct myGreat
{
bool operator()(int a... |
5,395,086 | 5,411,938 | Extract class from python | I'm writing a game in c++ using boost.python library as script system.
I have an abstract class Object. Now I create new class, inherit it from Objects and write somewhere Object *obj = new SomeCoolObject();
I also have a map of objects: map<string, Object*> objects. So after making object I do: objects.insert("name", ... | If you've already loaded the module (e.g., using boost::python::import("module_name")), you should be able to reference any classes in it via the attr() member function. Generally I write a wrapper function around it, since it can raise an exception if the class (or any other attribute, for that matter) doesn't exist. ... |
5,395,303 | 5,395,400 | PARITY_NONE a keyword in C++ Windows? | I am writing a serial library using boost and I have an enum:
enum parity_t { PARITY_NONE, PARITY_ODD, PARITY_EVEN };
I get errors like:
Error 1 error C2059: syntax error : '('
I couldn't figure out what the issue was. Then my friend and I tried:
void PARITY_NONE();
And we got these errors:
Error 1 error C214... | It's defined in winbase.h:
//
// Settable Stop and Parity bits.
//
#define STOPBITS_10 ((WORD)0x0001)
#define STOPBITS_15 ((WORD)0x0002)
#define STOPBITS_20 ((WORD)0x0004)
#define PARITY_NONE ((WORD)0x0100)
#define PARITY_ODD ((WORD)0x0200)
#define PARITY_EVEN ((WORD)0x0400)
#defin... |
5,395,498 | 5,395,520 | Visual Studio 2010 compiling .cpp files as .c files | I'm working one a Visual Studio solution which was generated using CMake (not sure if this is relevant).
In this solution there a c file, I wanted to change it into a cpp file, so I renamed it and changed the extension.
However, Visual Studio still treats it like a c file and gives compiler errors whenever I add any c+... | Project Properties, Configuration, C/C++, Advanced, change "Compile As".
|
5,395,503 | 5,517,755 | Required and Optional Arguments Using Boost Library Program Options | I'm using Boost Program Options Library to parse the command line arguments.
I have the following requirements:
Once "help" is provided, all the other options are optional;
Once "help" is not provided, all the other options are required.
How I can deal with this? Here is the my code handling this, and I found it's v... | I've run into this issue myself. The key to a solution is that the function po::store populates the variables_map while po::notify raises any errors encountered, so vm can be used prior to any notifications being sent.
So, as per Tim, set each option to required, as desired, but run po::notify(vm) after you've de... |
5,395,595 | 5,395,696 | Implementing Array Initializer | You can declare and initialize regular arrays on the same line, like so:
int PowersOfTwo[] = {1, 2, 4, 8, 16, 32, 64, 128};
Is there a way to replicate this behavior in custom classes? So, for example:
MyClass<int> PowersOfTwo = {1, 2, 4, 8, 16, 32, 64, 128};
You can have a copy constructor take an array as its para... | You can implement your class in such a way that you can write this:
MyClass<int> array;
array = 1,2,3,4,5,6,7,8,9,10;//dont worry - all ints goes to the array!!!
Here is my implementation:
template <class T>
class MyClass
{
std::vector<T> items;
public:
MyClass & operator=(const T &item)
{
items.cle... |
5,395,597 | 5,395,634 | C++ Inheritance error | Here's the code that triggers the error (Player.cpp):
#include "Library.h"
Player::Player(){
//generate player stats
str = rand()%6+1+1;
inte = rand()%6+1;
c = (rand()%6+1)+floor(str/3);
wis = rand()%6+1+floor(inte/4);
ref = rand()%6+1+floor(wis/4);
i = floor(ref/3);
hp = floor((str+(wi... | void Player::printStats() const
Should be, according to your headers:
void Entity::printStats() const
On the includes, do one of these, whichever suits your code best:
1.
Player.h must include Entity.h
Library.h should not include Player.h or Entity.h
Player.h and/or Entity.h can include Library.h if really needed.
... |
5,395,721 | 5,400,804 | Adding an OpenGL framework in Xcode 4 | I'm using Xcode 4 for my C++ programming. I want to add a framework, specifically an OpenGL framework, and I'm not quite used to where things are yet. It says in the help documentation that I should select the target, and from there I get the summery pane where I can add a linked framework/library. When I do that, the ... |
maybe go under "build phases" (instead of "summary") and then click "Link Binary With Libraries" and add button then search OpenGL.framework
im not sure 100%, im new to this too :)
|
5,395,837 | 5,395,887 | This application has requested the Runtime to terminate it in an unusual way. | Over the years, I've seen C++ applications the employ the "unusual way" language in a crash. For example:
This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
The first of these I debugged, it had something to do with a des... | This dialog is produced by the visual studio runtime, in response to abort(). abort() is by default called by e.g. terminate(). You'll get this from e.g. unhandled c++ exceptions, call to pure virtuals, failed assertions.
So, it's not platform dependent, but run-time library dependent. abort() is, by the c++ standard, ... |
5,395,882 | 5,395,905 | Templated class with a non-template base gives me a LNK2005 error | I have a templated class Child which inherits from a non-templated Parent class. When I include Child's header in multiple .cpp files I get a LNK2005 error. This happens because Parent gets defined in multiple compilation units. When those units get linked together they cause the LNK2005 error.
In case you're wonder... | You need to define int Parent::id = 0; just once in Child.C. By including it in the header it gets defined once per file that includes your header.
I suppose I should note that between the evils of putting it in Parent.C (matching class name) or Child.C matching the header name, I picked consistency. Much better is to ... |
5,395,992 | 5,396,047 | Exporting application to be runnable | I build applications using C++, C# and Java. But when I try to copy the output file to another machine it won`t work ... and for the Java, I have to copy the source code, install the SDK and jun it through the CMD or through a compiler ... I want to know how to use the .exe files created by C++ and C# to be used on oth... | In the case of .NET (C#) you don't need any compiler; build it as an exe, and ship that to any computer with a .NET runtime. For windows and MS .NET, just run it. For mono, you'll need to tell mono to run it:
mono my.exe
As it happens, the C# compiler (typically csc) is normally available in the framework, but you sho... |
5,396,120 | 5,397,921 | How to declare a vector of pointers in Cython? | I want to declare something like that:
cdef vector[Node*] list2node(list my_list):
But Cython gives me this error:
cdef vector[Node*] list2node(list my_list):
^
------------------------------------------------------------
mod.pyx:77:20: Expected an identifier or literal
| You shouldn't need the * -- vector[Node] should generate code for a vector of Node pointers. Using Cython 0.14.1:
cdef class Node:
pass
cdef vector[Node] list2node():
pass
cdef vector[int] test_int():
pass
cdef vector[int*] test_intp():
pass
Generates the C++ code:
static PyTypeObject *__pyx_ptype_3... |
5,396,178 | 5,396,187 | It's possible to make a program in Visual Studio C++ 2008 that not use the .NET framework? |
Possible Duplicate:
How do I create a native application using Visual C++ 2008?
Can I develop a program that not use the .NET Framework (Win32) in Visual Studio C++? For example like the ones in Visual Studio C++ 6?
| Yes. File, New Project, go to Visual C++/Win32 in the tree, select one of the win32 project types.
|
5,396,280 | 5,396,651 | Unable to get height/width of a widget - gtkmm | I'm writing an application using gtkmm.
I wrote a simple widget class, that I want to display in the application's main window only in some cases. Otherwise, I would like a Label "disabled" to be visible.
To achieve that I packed both the widget and the label into one VBox, and I show() and hide() them in order to swa... | I haven't done much in gtkmm, more in pygtk. But I think to get meaningful values from get_width/get_height, a widget must be realized, which is an X-window speak for visible. And I guess your widgets are not yet visible in window constructor.
I'd propose you to use a gtk.Notebook instead, with its tabs hidden. Then gt... |
5,396,382 | 5,396,410 | Slow down associated with vector::push_back and placement new in a multithreaded application | I have a multithreaded application in which my thread utilization is very poor (in the ball park of 1%-4% per thread, with fewer threads than processors). In the debugger, it appears to be spending a lot of time in vector::push_back, specifically the placement new that occurs during the push_back. I've tried using re... | Unless you need these initialized to 0, consider writing a vector-like class which does not initialize. I've found this to provide measurable performance gains in some scenarios.
Side note: When your profiler claims you're spending most your time with primitive operations on 64-bit integers, you know the rest of your c... |
5,396,440 | 5,410,460 | GLSL: How to access nearby vertex colors? (bilinear interpolation without uniforms) | I'm trying to make bilinear color interpolation on a quad, i succeeded with the help of my previous question on here, but it has bad performance because its requires me to repeat glBegin() and glEnd() and 4 times glUniform() before glBegin().
The question is: is it anyhow possible to apply bilinear color interpolation ... | Long story short: You cannot do this with a vertex shader.
The interpolator (or rasterizer) is one of the components of the graphics pipeline that is not programmable. Given how the graphics pipe works, neither a vertex shader nor a fragment shader are allowed access to anything but their vertex (or fragment, respecti... |
5,396,471 | 5,396,647 | Storing text from a file | My file contains the following code:
test.asm
^^^^^^^^^^^^^^^^
!START:
!LDA #97
!LDX #$A000
!STA, X
!END
I store the above code in my program in a string called sourcecode.
Every Label (kind of a keyword for me here) begins with an ! mark.
Thus, START / LDA / LDX / STA / END are labels which i would like to store.
Now... | 6502 assembly - what fun!
As tenfour says, a vector is good for compact and relatively immutable storage and access, but your usage over the lifetime of your app should guide your selection. (The good news is that if you use STL iterators, you should be able to switch container types with little impact on the rest of ... |
5,396,474 | 5,396,553 | Declaration of Volatile Pointer Array in C++ | I have a struct called Ambigous, and inside the struct I have an array of pointers to other Ambigous.
I want to use OSAtomic.h library, to do CompareandSwaps.
However I am having trouble getting the array to play nice.
OSAtomicCompareAndSwapPtrBarrier(void *__oldValue, void *__newValue,
void *volatile *__theValue)
... | Perhaps you want
bool res = OSAtomicCompareAndSwapPtrBarrier(
current_node, new_node, local->list + pos);
Note that the CAS operation is basically
bool CAS(void* old, void* new_, void* volatile* val) {
/*atomic*/ {
if (old == *val) {
*val = new_;
return true;
} else
... |
5,396,598 | 5,407,959 | tbb::concurrent_vector returns wrong size | I've asked this question on a TBB forum, but I'm hoping someone here might have some additional thoughts. I was debugging an issue we're seeing and noticed some strange behavior from tbb::concurrent_vector.
The bottom line is that after a push_back() call actually completes, the size() of the concurrent_vector does ... | I ended up solving this issue. It turns out it is 'by-design' in concurrent_vector. See this link for a forum response about it.
|
5,396,634 | 5,396,748 | Is an Iterator to vec.end() still valid after vec.push_back() when there is no reallocation | Is this example code valid?
#include<vector>
using namespace std;
int main() {
vector<int> vec(10); // create with 10 elements
vec.reserve(100); // set capacity to 100
vector<int>::iterator iter = vec.end(); // points 1 past vec[9]
vec.push_back( 777 );
bool is_this_valid_and_true = *iter == vec[10]; /... | You are thinking of iterators as pointers.
Iterators may use pointers as an implementation detail but they are not actual pointers.
Thus:
iter = vec.end() + 1; // This is not valid.
There is no such thing as two elements passed the end of data.
vec.end() returns an iterator that when decrement is a reference to the la... |
5,396,790 | 5,396,905 | Concatenate strings in function call c++ | I'm trying to create a logger function where you can pass in a message which will be logged to a text file. Sometimes I'd like to pass in a variable concatenated with my message so I could do something like:
logger("The variable is: " + variable);
The function is defined as
void logger(std::string message);
I'm using... | Why not just do something like this:
QString qs = "hello";
qs.toStdString();
As far as concatenating on the fly, I like to use a simple formatter class:
class Formatter
{
public:
template<class Val> Formatter& operator<<(const Val& val)
{
ss_ << val;
return * this;
}
operator string () ... |
5,397,087 | 5,397,150 | How to change text output depending on the value of x | I want to create a list from one to ten. Each time it loops it adds one to x, I also want it to print like this.
1
2
3
4
5
6
7
8
9
10
Right now it prints like this:
1
2
3
4
5
6
7
8
9
10
| pseudocode:
for (i: 1..10)
for(j:1..i) //or for(j:1..(i-1)) if you want zero spaces on line 1
print space
print i
print newline
hth
|
5,397,178 | 5,397,241 | What is the cost of compiling a C program with a C++ compiler? | I want to use C with templates on a embedded environment and I wanted to know what is the cost of compiling a C program with a C++ compiler?
I'm interested in knowing if there will be more code than the one the C compiler will generate.
Note that as the program is a C program, is expect to call the C++ compiler withou... | There's probably no 'cost', assuming that the two compilers are of equivalent quality. The traditional objection to this is that C++ is much more complex and so it's more likely that a C++ compiler will have bugs in it.
Realistically, this is much less of a problem that it used to be, and I tend to do most of my emb... |
5,397,447 | 5,398,498 | Struct padding in C++ | If I have a struct in C++, is there no way to safely read/write it to a file that is cross-platform/compiler compatible?
Because if I understand correctly, every compiler 'pads' differently based on the target platform.
| No. That is not possible. It's because of lack of standardization of C++ at the binary level.
Don Box writes (quoting from his book Essential COM, chapter COM As A Better C++)
C++ and Portability
Once the decision is made to
distribute a C++ class as a DLL, one
is faced with one of the fundamental
weaknesses ... |
5,397,616 | 5,397,837 | What is wrong with `std::set`? | In the other topic I was trying to solve this problem. The problem was to remove duplicate characters from a std::string.
std::string s= "saaangeetha";
Since the order was not important, so I sorted s first, and then used std::unique and finally resized it to get the desired result:
aeghnst
That is correct!
Now I ... | In GCC (libstdc++), remove_if is implemented essentially as
template<typename It, typename Pred>
It remove_if(It first, It last, Pred predicate) {
first = std::find_if(first, last, predicate);
// ^^^^^^^^^
if (first == last)
return first;
else {
... |
5,397,782 | 5,397,935 | Using __LINE__ macro as a template parameter in visual studio | I expected the following code to work, but I received a compile error:
error C2975: 'n' : invalid template argument for 'foo', expected compile-time constant expression
#include <iostream>
using namespace std;
template<int N>
struct foo
{
foo() { cout << N << endl; }
};
int main()
{
foo< __LINE__ > f;
}
W... | Works for me in VS 2010 10.0.40219.1 SP1Rel and in Ideone
But MSDN mentions problems which result in C2975, if using __LINE__ in template with compiler-option /ZI: MSDN C2975
Edit: Sorry, I linked the german version, here in english
|
5,397,848 | 5,452,652 | Mouse/Keyboard input in OSX without Cocoa | I am writing an application in C++ using CGL/OpenGL, and need keyboard/mouse input. I was trying to avoid Objective-C and Cocoa if possible. I am aware that one can capture input using Carbon, but seems that Carbon is slowly being phased out, plus it is not clear if it plays well with 64-bit applications. Does anybody ... | Quartz event taps might do what you want. Without knowing why you are trying to avoid using the Cocoa event system it's hard to know what technology would be best for what you are trying to do.
|
5,397,881 | 5,398,059 | Tinythread++: getting thread ID | This is how you get it printed to the terminal.
cout << "Current thread ID: " << this_thread::get_id() << endl;
Of course when there are multiple threads the output becomes interleaved and impossible to figure out. So I wanted to log each thread's output to its own file. But I need the thread ID to give a name to the... | Use std::stringstream
#include <sstream>
std::stringstream s;
s << "File_Name:_" << this_thread::get_id();
std::ofstream file(s.str().c_str());
|
5,397,976 | 5,398,013 | Multidimensional array as a flat array problem | I'm looking at two lines of code that somebody wrote and there is an exception in the 2nd one, however I don't understand why.
char** array = (char**) new char [2] [6];
std_strlprintf(array[0],6,"[%d]", num);
std_strlprintf is a Brew function that writes formatted output to a string. (num is an integral value which i... | Two-dimensional array is not the same as array of pointers.
Your first statement creates two arrays of six chars each as a single memory block. Replace that statement with:
char (*array)[6] = new char [2][6];
and you'll be all set with your second statement. Don't forget to
delete [] array;
Edit 0:
Huh, I should've k... |
5,398,280 | 5,398,373 | Array balancing point | What is the best way to solve this?
A balancing point of an N-element array A is an index i such that all elements on lower indexes have values <= A[i] and all elements on higher indexes have values higher or equal A[i].
For example, given:
A[0]=4 A[1]=2 A[2]=7 A[3]=11 A[4]=9
one of the correct solutions is: 2. All ele... | Start by assuming A[0] is a pole. Then start walking the array; comparing each element A[i] in turn against A[0], and also tracking the current maximum.
As soon as you find an i such that A[i] < A[0], you know that A[0] can no longer be a pole, and by extension, neither can any of the elements up to and including A[i]... |
5,398,307 | 5,398,504 | Sum of decimal digit | The following was a programming interview practice question.
What is the smart way to handle this?
A number M is stored in an array in the reverse order. For example, the number 274 is stored in the following array:
A[0]= 4 A[1]=7 A[2]=2
Write a function that given the array A representing some number, returns the s... | The following code will do this in O(n).
#include <iostream>
#include <vector>
int times_17_dec_digits_sum(const vector<int> &A)
{
int sum = 0, carry = 0;
for (int i = 0; i < A.size(); i++) {
int perdigitsum = A[i]*17+carry;
sum += perdigitsum % 10;
carry = perdigitsum / 10;
}
... |
5,398,359 | 5,398,580 | Problem implementing threads in a program | I have the following program:
#include "stdafx.h"
#include <boost/thread/thread_time.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
using namespace std;
class DogDoor {
bool open;
public:
DogDoor()
{
this->open = false;
}
void Open()
{
cout << "The dog door opens" <... | You need to make the main thread wait until the door is open:
class DogDoor
{
bool open;
public:
// If you want to go through this door you should call
// this method. If the door is not open you are suspended.
// until somebody opens the door.
void goThroughDoor()
{
boost::unique_lock<... |
5,398,544 | 5,398,944 | pass and return multi-dimensional arrays from a function in C++ | I am trying to write a function that takes two matrices as parameters and return the sum of these two matrices.
The following is the code, which fails to pass the compiler. I think the implementation of function is wrong, how to correct it?
#include <iostream>
int **func(int **array1, int **array2, int n){
a1 = ne... | #include <iostream>
using namespace std;
int** Create2DMatrix(int);
int** AddMatrix(int**&,int**&,int);
void DeleteMatrix(int**&);
int main( )
{
int myDimension=4; // for example
int i,j;
int** myFirstMatrix=Create2DMatrix(myDimension);
int** mySecondMatrix=Create2DMatrix(myDimension);
... |
5,398,673 | 5,399,464 | any good and simple RPC library for inter-process calls? | I need to send a (probably one) simple one-way command from client processes to server process with arguments of builtin C++ types (so serialization is pretty simple). C++, Windows XP+.
I'm looking for a library that doesn't require complicated configuration, provides simple interface, doesn't require hours to days of ... | I don't think sockets are really overkill. The alternatives all have their own problems and sockets are far better supported than named pipes, shared memory, etc., because almost everyone is using them. The speed of sockets on local system is probably not an issue.
There's Apache Thrift:
http://incubator.apache.org/t... |
5,398,930 | 5,399,014 | General rules of passing/returning reference of array (not pointer) to/from a function? | We can pass reference of an array to a function like:
void f(int (&a)[5]);
int x[5];
f(x); //okay
int y[6];
f(y); //error - type of y is not `int (&)[5]`.
Or even better, we can write a function template:
template<size_t N>
void f(int (&a)[N]); //N is size of the array!
int x[5];
f(x); //okay - N becomes... | If you want to return a reference to an array from a function, the declaration would look like this:
// an array
int global[10];
// function returning a reference to an array
int (&f())[10] {
return global;
}
The declaration of a function returning a reference to an array looks the same as the declaration of a var... |
5,398,987 | 5,401,172 | Is it expected that use of boost::thread_specific_ptr<>::get() be slow? Any work arounds? | I'm currently profiling an application with performance problems using Valgrind's "Callgrind". In looking at the profiling data, it appears that a good 25% of processing time is being spent inside of boost::detail::get_tss_data in an application whose primary purpose is physics simulation and visualization.
get_tss_dat... | thread_specific_ptr uses pthread_setspecific/pthread_getspecific for POSIX systems which is not the fastest possible.
If you are on a POSIX system, you can use the __thread storage specifier. However, it can only be used with initializers that are constant expressions e.g gcc's __thread
For Windows, a similar specifie... |
5,399,040 | 5,399,073 | Help with constructor (pusing_back elements into a pointer to an array) | I have a problem inserting elements into a pointer to a vector of some elements I defined in my code (in this case Recipes). In some other parts of the code, using push_back seems to work fine, but if I use it in this code:
{
Recipe defaultRec;
this->recipes_ = new vector<Recipe>;
this->recipes_->push_back... | Your code looks fine to me. I'm sure the problem is somewhere else.
By the way, why do you use pointer to vector? Why not this:
vector<Recipe> recipes_; //member
Recipe defaultRec;
recipes_.push_back(defaultRec);
Atleast this saves you from allocation and deallocation. Besides, most likely, pointer to vector doesn't ... |
5,399,153 | 5,399,611 | C++ to F# smooth translation | Hey folks, I have the following piece of code from C++.
for (int i=0; i < nObstacles; i++)
{
int x,y;
bool bAlreadyExists;
do {
x = rand() % nGridWidth;
y = rand() % nGridHeight;
} while (HasObstacle(x, y));
SetObstacle(x, y, true);
}
I can translate it to F# dir... | Here is my try:
Seq.initInfinite (fun _ -> rnd.Next(width), rnd.Next(height))
|> Seq.filter (fun (x, y) -> IsEmptyAt x y)
|> Seq.distinct
|> Seq.take nObstacles
|> Seq.iter (fun (x, y) -> board.[x,y] <- Obstacle)
You can remove the Seq.filter if the board is empty at the beginning. Like in Tomas solution, it generates... |
5,399,225 | 5,399,254 | How does cout work when given an array? |
Possible Duplicate:
Why does cout print char arrays differently from other arrays?
If I have this code:
char myArray[] = { 'a', 'b', 'c' };
cout << myArray;
It gives me this output:
abc
However, if I have this code:
int myArray[] = { 1, 2, 3 };
cout << myArray;
It gives me this output:
0x28ff30
Why does it not pri... | The reason that the first piece of code works is that the compiler is implicitly converting the array into a const char * character pointer, which it's then interpreting as a C-style string. Interestingly, this code is not safe because your array of characters is not explicitly null-terminated. Printing it will thus ... |
5,399,467 | 5,399,880 | Are there any guidelines on migrating from C to C++ | I would like to know if you have some links to guidelines to migrating from C to C++.
I'm mainly interested in the constructions to check in the C code that could have problems the compiler can not detect? And what are the workarounds?
Note: Please don't answer with things the compiler is able to detect.
| One way to investigate this is just to read through some lists of incompatibilities between C and C++, and see which ones produce run-time issues rather than compilation issues. Such lists are plentiful, good starting places might be:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
http://david.tribble.co... |
5,399,551 | 5,399,790 | Is it safe to emit a sigc++ signal in a destructor? | My current project has a mechanism that tracks/proxies C++ objects to safely expose them to a script environment. Part of its function is to be informed when a C++ object is destroyed so it can safely clean up references to that object in the script environment.
To achieve this, I have defined the following class:
clas... | The c++ spec guarantees that the data members in your object will not be destroyed until your destructor returns, so the onDelete object is untouched at that point. If you're confident that the signal won't indirectly result in any reads, writes or method calls on the object(s) being destroyed (multiple objects if the... |
5,399,580 | 5,399,642 | 'undefined reference to vtable' for abstract class (Qt) | I'm writing a library for parsing expressions into a tree structure and I have an abstract type QCExpressionNode as my base class. It looks like this:
#ifndef QCEXPRESSIONNODE_H
#define QCEXPRESSIONNODE_H
#include <QString>
class QCExpressionNode
{
public:
virtual ~QCExpressionNode() {}
virtual float evaluat... | #include <QtPlugin>, then the file should compile just fine.
Q_DECLARE_INTERFACE is declared in QtPlugin.
By the way: it's quite unusual to compile header files by themselves and it's unusual to have include guards outside header files.
|
5,399,591 | 5,400,138 | Max Repeated Word in a string | I was trying to do a very common interview problem "Finding the max repeated word in a string " and could not find much resources in net for c/c++ implementation. So I coded it myself here.
I have tried to do most of the coding from scratch for better understanding.
Could you review my code and provide comments on my ... | Just for the sake of comparison, the most obvious way to do this is C++ is:
#include <map>
#include <string>
#include <iostream>
#include <sstream>
int main()
{
std::istringstream input("I am am am good good");
std::map<std::string, int> count;
std::string word;
decltype(count)::const_iterator most_com... |
5,399,599 | 5,399,662 | Dynamic array and void pointers | I have quite peculiar problem. I want initialize an array pointed by a void pointer to which memory is allocated using new as shown below.
const int ARRAY_SIZE = 10;
void InitArray()
{
int *ptrInt = new int[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE;i++)
{
ptrInt[i] = 1; //OK
}
void *ptrVoid ... | You have an order of operations problem (and an extra *). Try this inside your second loop:
((int *)ptrVoid)[i] = 1;
|
5,399,844 | 5,399,992 | My c++ software is a collection of too many exe's, how do I manage it | I wrote a c++ program to do a variety of things. I realized that some of the software should be targeted for x86 (because it uses a 3rd party library that can only be compiled on x86), and then the rest of the software should be targeted for x64, and the two exe's communicate through shared memory. I then added a 3rd e... | As long as the user only has to launch one of them, which then launches the others invisibly, there's nothing wrong with this at all, and in fact it's rather common.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.