question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,753,390 | 3,753,421 | How to understand the following c++ code? | inpfile>>ch;
if(ch<16) outfile<<"0×0"<<std::hex<<setprecision(2)<<(int)ch<<" ";
what does std::hex<<setprecision(2) mean?
| iostreams can be manipulated to achieve the desired formatting - this is done by what at first sight looks like outputting predefined values to them as shown in our subject line of code.
std::hex displays following integer values in base16.
setprecision sets the precision for display of following floating values.
Fur f... |
3,753,474 | 3,753,487 | C++: How does string vectors' random access time work? | I know a simple int vector have O(1) random access time, since it is easy to compute the position of the xth element, given all elements have the same size.
Now whats up with a string vector?
Since the string lengths vary, it can't have O(1) random access time, can it? If it can, what is the logic behind it?
Thanks.
Up... | The vector does have O(1) access time.
String objects are all the same size (on a given implementation), regardless of the size of the string they represent. Typically the string object contains a pointer to allocated memory which holds the string data.
So, if s is a std::string, then sizeof s is constant and equal to ... |
3,753,495 | 3,833,646 | SWIG: How to wrap std::string& (std::string passed by reference) | I am using SWIG to access C++ code from Java.
What is the easiest way to expose a std::string parameter passed by non-const reference?
I have primitives passed by reference exposed as Java arrays, thanks to typemaps.i, and const std::string&s exposed as java.lang.String, thanks to std_string.i. But a non-const std::str... | The best approach I could find was to write my own typemap. I had been hoping for a few trivial SWIG instructions.
In case anyone else needs this, here's how I did it. Bear in mind that I am not a SWIG expert.
First, you need to define some typemaps to be applied to std::string& arguments. You only have to define the... |
3,753,688 | 3,754,394 | Selecting a flavor of classes to implement a function at run-time? | I want to send data and a capability description to a remote site. Upon receiving the data at the remote site, I want to look at the description and create an object (via a factory method ) doing exactly what I want when I invoke exec on it.
Examples:
1) send [3, (add 5) ] => receive(obj); obj->exec() -> 8
2) send [3... | You say that you don't want to build separate classes for different permutations of abilities, to which I agree. But can you separate out your "abilities" into a set of atomic operations, and another set of combinators. If they all derive from a common 'executor' object, with a virtual 'exec' method, that might do the... |
3,753,716 | 3,753,839 | Can't instantiate an istring_iterator using a wistringstream | I'm trying to split a string using the method found in this thread, but I'm trying to adapt it to a wstring. However, I have stumbled upon a weird error. Check the code:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main(vo... | Per the latter part of the error message, you have to override the default params 2 and 3 on istream_iterator() to match widechar usage elsewhere. In Visual C++ this version compiles OK for me:
copy(istream_iterator<wstring, wchar_t, std::char_traits<wchar_t> >(iss), // I DO NOT GET THE ERROR HERE
istream_iterator... |
3,753,725 | 3,754,058 | Can we split, manipulate and rejoin a string in c++ in one statement? | This is a bit of a daft question, but out of curiousity would it be possibly to split a string on comma, perform a function on the string and then rejoin it on comma in one statement with C++?
This is what I have so far:
string dostuff(const string& a) {
return string("Foo");
}
int main() {
string s("a,b,c,d,e,f")... | First, note that your program writes "Foo,Foo,Foo,Foo,Foo,Foo,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,," to your result string -- as already mentioned in comments, you wanted to use back_inserter there.
As for the answer, whenever there's a single value resulting from... |
3,753,757 | 3,753,866 | Is it ever impossible to write a header-only library? | Is there ever such a pattern of dependancies that it is impossible to keep everything in header files only? What if we enforced a rule of one class per header only?
For the purposes of this question, let's ignore static things :)
| I am aware of no features in standard C++, excepting statics which you have already mentioned, which require a library to define a full translation unit (instead of only headers). However, it's not recommended to do that, because when you do, you force all your clients to recompile their entire codebase whenever your l... |
3,754,153 | 3,754,176 | C++ function parameter as reference | I have a question. Can anyone tell me why someone would declare parameter r like that ?
Whats the difference between Record& r and Record(&r) ?
QDataStream& operator>>(QDataStream &s, Record(&r))
{
}
Thanks :)
| Record(&r) and Record &r are identical type declarations. I don't know why somebody would include the parentheses except for stylistic reasons. Perhaps it's some cruft left over from a refactoring?
|
3,754,268 | 3,757,093 | Returning string to JavaScript from C++ function | I have a class (JSObject) that implements the IDispatch interface. The class is exposed to JavaScript running in my hosted web browser control (IWebBrowser2).
See more here about how this works: Calling C++ function from JavaScript script running in a web browser control
I can call in to JSObject from my JavaScript cod... | The first MultiByteToWideChar() call returns the amount of characters needed to store the string, including the null-terminator. Then SysAllocStringLen() allocates a buffer for lenW+1 characters (one more than needed) and already null-terminates it.
As the MultiByteToWideChar() also writes a null-terminator, you end ... |
3,754,362 | 3,754,508 | Boost.Bind - understanding placeholders | I am trying to understand the following example, that is similar (but not equal) to the one posted earlier on the SO Help understanding boost::bind placeholder arguments :
#include <boost/bind.hpp>
#include <functional>
struct X {
int value;
};
int main() {
X a = { 1 };
X b = { 2 };
boost::bind(... | arguments are packed in tuple (a,b) and passed to functors. then inner functor decides which tuple element it needs, e.g. try:
boost::bind(&X::value, _1)(a,b)
boost::bind(&X::value, _2)(a,b)
More generally, every value, regardless if it is constant/reference/placeholder is represented as functor which takes argument ... |
3,754,432 | 3,754,443 | C++ function returning value as reference and return *this | if I wanted to return "this" from a class member function as reference would this piece of code be correct ?
Record& operator=(const Record& that) {
m_name = that.m_name;
return *this;
}
Shouldn't i just use "return this" ?
Thanks for help :)
| Yup, that's correct.
Return this wouldn't work since this is a pointer. (The reason it's a pointer and not a reference is because references weren't introduced into the language until after classes.)
In this specific case, if you're just going to assign the members anyway you shouldn't write a copy assignment operator;... |
3,754,640 | 3,805,864 | Inaccurate Mouse Coordinates Returned | The issue is that the further the mouse click is from the top left origin (0,0) the greater the height inaccuracy when the vertex is plotted. Any ideas?
int WindowWidth = 19;
int WindowHeight = 13;
int mouseClickCount = 0;
int rectPlotted;
GLint x1;
GLint y1;
GLint x2;
GLint y2;
//Declare our functions with prototypes... | I was compiling and running my code within Parallels VM v.6. This was the issue leading to inaccurate mouse coordinates being returned. I compiled and ran the exact same code on OS X without problem.
|
3,754,827 | 3,755,086 | Resource recommendations for Windows performance tuning (realtime) | Any recommendations out there for Windows application tuning resources (books web sites etc.)?
I have a C++ console application that needs to feed a hardware device with a considerable amount of data at a fairly high rate. (buffer is 32K in size and gets consumed at ~800k bytes per second)
It will stream data without u... | The best you can hope for on commodity Windows is "usually meets timing requirements". If the system is running any processes other than your target app, it will occasionally miss deadlines due scheduling inconsistencies. However, if your app/hardware can handle the rare but occasional misses, there are a few things yo... |
3,754,932 | 3,754,996 | Normal function not overwriting template function | I have to use an external library, but am getting a "multiple definition error" from following template function and its explicit specialization, if it gets called with a std::string.
template <typename T>
void foo(T& value);
template <>
void foo(std::string& value);
even if I change the 2nd function to
void foo(std:... | You're breaking the one-definition rule.
Unless a function is inline, it can only be defined once. If you mark the function as inline, so long as the definitions match they can be defined as often as desired. Template functions behave as if they were implicitly inline, so you don't get errors with templates.
However, a... |
3,754,933 | 3,754,957 | volatile + object combination disallowed in C++? | I'm using an embedded compiler for the TI TMS320F28335, so I'm not sure if this is a general C++ problem (don't have a C++ compiler running on hand) or just my compiler. Putting the following code snippet in my code gives me a compile error:
"build\main.cpp", line 61: error #317: the object has cv-qualifiers that are ... | In the same way you cannot do this:
struct foo
{
void bar();
};
const foo f;
f.bar(); // error, non-const function with const object
You cannot do this:
struct baz
{
void qax();
};
volatile baz g;
g.qax(); // error, non-volatile function with volatile object
You must cv-qualify the functions:
struct foo
{
... |
3,755,002 | 3,755,173 | Debug assertion failed | I keep encountering this "Debug assertions failed!" error when I run my program in debug mode. I tried looking this error up on the visual C++ website but the explanations are too advanced for me and they don't have any resemblance to what my best guess as to the problem is.
I have went through my code and narrowed dow... | Your code is corrupting the heap. The first snippet is from the C runtime library, the assert is telling you that your program is passing a bad pointer value to the delete operator.
Commenting out the delete statements merely hides the problem. It will come back to haunt you a different way when you keep developing t... |
3,755,122 | 4,415,266 | CppUnit (or C++ unit tests in general) in Xcode | I've written some ObjC unit tests for use with the OCUnit support in Xcode. Now I would like to do the same for some of the C++ code I'm about to write (a separate static library).
Is there any support for e.g. CppUnit (or some other C++ test framework) in Xcode? When I write support, I mean I want to run the tests and... | Have you looked at Google C++ Testing Framework? That one should be pretty portable.
|
3,755,204 | 4,277,122 | Translate drive letter to full path for CD burner | In the following code, I am trying to get a folder location from the user. However, when I selected E:\ in the folder browser, szAbsolutePath doesn't give me the path for the CD burner temporary folder. This prevents me from saving to this location. However, if I choose something like E:\folder1\, I get the full path a... | You can use the ICDBurn::GetRecorderDriveLetter function to get the recorder's drive letter - then it's trivial to compare against the string you get back from GetSaveFileName(). If you do get back a path on the CD burner, you can use SHGetFolderLocation with CSIDL_CDBURN_AREA to get the path of the staging area - then... |
3,755,370 | 3,755,438 | how can to allocate a matrix using vector on the heap | hey, i am trying to allocate a dynamic matrix on the heap and seems like i am doing something wrong.
i try to do the following thing :
vector< vector<int*> >* distancesMatrix=new vector< vector<int*> >;
it does allocate a matrix on the heap but the matrix itself is empty, i want the matrix to be sizeXsize but cant ... | Try vector< vector<int> >(size, size).
|
3,755,711 | 3,755,731 | How to fix a linking bug? | hey, sorry for this but i'm trying to figure out what's the problem for too long, if you can spot a clue from this long error message i will be thankful
Error 6
error LNK2019: unresolved external symbol "public: __thiscall Adjutancy::Adjutancy(class std::set<class Vehicle *,struct CompareCatId,class std::allocato... | Adjutancy's constructor is not being compiled. You may not be compiling a source file, or maybe you have forgotten to implement this function.
If you want better responses, post your code.
By the way, the signature for the constructor in question probably looks something like this:
Adjutancy::Adjutancy(set<Vehicle *,C... |
3,756,024 | 3,759,240 | Compiling a large C++ library into Android NDK using JNI - Makefile Questions | I'm trying to compile a C++ library (VRPN) with a couple of Java wrappers to be used in an Android app. Using the ndk-build command, I get an "undefined reference" error for the first line of my C++ interface file which references a constructor for an object in the library. I am fairly sure my code is correct - the c... | I guess you forgot to add the other cpp files, so the linker is not able to find the symbols. So add vrpn_Button.cpp and vrpn_Connection.cpp to your Android.mk:
LOCAL_SRC_FILES := \
jni_vrpn_button.cpp \
vrpn_Button.cpp \
vrpn_Connection.cpp
It's the same for all makefiles, i.e. not limited to Android.
|
3,756,144 | 3,756,216 | Using the pagefile for caching? | I have to deal with a huge amount of data that usually doesn't fit into main memory. The way I access this data has high locality, so caching parts of it in memory looks like a good option. Is it feasible to just malloc() a huge array, and let the operating system figure out which bits to page out and which bits to kee... | Assuming the data comes from a file, you're better off memory mapping that file. Otherwise, what you end up doing is allocating your array, and then copying the data from your file into the array -- and since your array is mapped to the page file, you're basically just copying the original file to the page file, and in... |
3,756,250 | 3,785,356 | std::map broken in alchemy? | The following code tests the use of std::map with std::string as a key:
#include <stdio.h>
#include <map>
#include <string>
using namespace std;
typedef map<string, int> test_map_t;
int main(int argc, char **argv) {
test_map_t test_map;
test_map["test1"]= 1;
test_map["test2"]= 2;
test_map["test3"... | class string is broken in alchemy. There is a bug in operator copy (=). map works fine with other class
|
3,756,279 | 3,756,364 | Unexpected output from Clang | I've been testing out clang-llvm to see if it is worth it to mention to my school's IT department to add it to the machines we students program on. For all of our assignments, we are required to compile using g++ -Wall -W -pedantic-errors *.cpp, so I just converted the command to clang++ -Wall -W -pedantic-errors. I go... | I kinda agree with Mike, but for getting-off-the-ground's sake, try this:
clang++ -Wall -W -pedantic-errors -Wno-unused-variable
I haven't used llvm much but I think the point of the [-Wunused-variable] in the diagnostic is to tell you that you can shut that warning up with -Wno-unused-variable.
|
3,756,286 | 3,756,406 | How to convert a char array to a list of HEX values? | Would I would like to be able to do is convert a char array (may be binary data) to a list of HEX values of the form: ab 0d 12 f4 etc....
I tried doing this with
lHexStream << "<" << std::hex << std::setw (2) << character << ">";
but this did not work since I would get the data printing out as:
<ffe1><2f><ffb5><54>< 6... | As Zack mentions, The 4-byte values are because it is interpreting all values over 128 as negative (the base type is signed char), then that 'negative value' is extended as the value is expanded to a signed short.
Personally, I found the following to work fairly well:
char *myString = inputString;
for(int i=0; i< lengt... |
3,756,422 | 3,756,447 | How to catch an assert with Google test? | I'm programming some unit test with the Google test framework. But I want to check whether some asserts are well placed and are useful. Is there a way to catch an assert in Google test?
Example code under test:
int factorial(int n){
assert(n >= 0);
//....
}
And then the test:
#include <gtest/gtest.h>
TEST(Fact... | Google test provides ASSERT_DEATH, EXPECT_DEATH and other related macros.
This question and What are Google Test, Death Tests are each other's answers. Does that make them duplicates, or not? ;-)
|
3,756,538 | 3,756,558 | Source Code Dependencies | Suppose I have a bunch of C++ files: A.cc, B.cc, C.cc, and their associated header files. A.cc makes use of classes in B.cc and so on.
Now say I want to build the source files. After the preprocessing phase, can I theoretically compile (not link) all the files simultaneously? (A.cc -> A.obj, ...)
I'm just wondering if... | No, unless you're doing something weird indeed, the compilation of B.cc will not depend on the result of compiling A.cc (and vice versa). That's why make -j (running multiple "jobs", i.e., processes, in parallel, each compiling a file at the same time) is a popular usage, especially of course on multi-core machines (b... |
3,756,621 | 3,758,416 | Linking phase in distcc | Is there any particular reason that the linking phase when building a project with distcc is done locally rather than sent off to other computers to be done like compiling is? Reading the distcc whitepages didn't give a clear answer but I'm guessing that the time spent linking object files is not very significant compa... | The way that distcc works is by locally preprocessing the input files until a single file translation unit is created. That file is then sent over the network and compiled. At that stage the remote distcc server only needs a compiler, it does not even need the header files for the project. The output of the compilation... |
3,756,627 | 3,756,651 | Search for a word in a file and replace it in C? | How could I search for a word in a certain file, and then replace that word with a different string of text. Like for example: In this paragraph find the word iPad and replace it with iPhone. I would like a code sample in C (or C++ if it is not possible without a third party library).
| Pseudocode:
while (not end of inputFile) {
line = inputFile.readline()
line = line.replace("iPad", "iPhone")
tempFile.writeline(line)
}
inputFile.close()
tempFile.close()
delete inputFile
rename tempFile to inputFile
|
3,756,746 | 3,756,808 | Get System Time and User Time | I'm working on linux and am using the values in /proc//stat to log performance data. I am currently logging process user time and process system time. The problem that I have run into is that the code puts out correct values on ubuntu 10.04 but seems to be wrong under fedora 13.
Under fedora it looks like the counter f... | If you want to know CPU time from the process itself (or a parent), you can use times():
clock_t times(struct tms *buf);
struct tms {
clock_t tms_utime; /* user time */
clock_t tms_stime; /* system time */
clock_t tms_cutime; /* user time of children */
clock_t tms_cstime; /* system time of children ... |
3,756,770 | 3,756,831 | How can I efficiently draw thousands of vertices? | I'm currently writing an interactive simulator which displays the evolution of a system of particles. I'm developing on Windows 7 32-bit, using Visual Studio.
Currently, I have a function to draw all the particles on screen that looks something like this:
void Simulator::draw()
{
glColor4f(255, 255, 255, 0);
gl... | The very first optimization you should do is to drop glBegin/glEnd (Immediate mode) and move to Vertex Arrays (VAs) and Vertex Buffer Objects (VBOs).
You might also want to look into Point Sprites to draw the particles.
|
3,757,001 | 3,757,218 | OpenGL ES 2 - load and display image | I'm having trouble finding any examples of OpenGL ES 2 (C++) loading/displaying images. Been looking for last 3 hours but all I found so far is for iPhone or "Look Ma! A triangle!" or it's unbelievably complicated (at least for me).
I'm just looking for something super easy (for a not very smart person). All I need is ... | You didn't specify what platform.
Loading of images is the process of reading a binary file format and possibly decompressing the data. That is not part of the OpenGL or OpenGL-ES spec.
If you want to load and display textures, the easiest way to do it is use some library that already does all the hard work for you. ... |
3,757,108 | 3,757,116 | Contents of a static library | I have a static library, say mystaticlib.a. I want to see its contents, such as the number of object files inside it.
How can I do this on gcc?
| On gcc, use ar -t.
-t option of the gnu archiver (ar) writes a table of contents of archive to the standard output. Only the files specified by the file operands shall be included in the written list. If no file operands are specified, all files in archive shall be included in the order of the archive.
More info here.
|
3,757,255 | 3,757,310 | how to pass C++ variables to Insert of c++ using Mysql ++ | I am struggling with the code from few days can anyone help
std::string str=uri_req1.substr(found+1);
char query[2000];
sprintf(query,"Insert into publish VALUES('%s','NO')",str);
I am getting following warnings and value is not inserted in the tables
warning: cannot pass objects of non-POD type ‘struct std::string’
t... | I'd probably use a stringstream to assemble the string:
std::ostringstream query;
query << "Insert into publish values('" << str << "', 'NO')";
mysql_query(&mysql, query.str().c_str());
|
3,757,270 | 3,757,295 | Most Efficient way to 'look up' Keywords | Alright so I am writing a function as part of a lexical analyzer that 'looks up' or searches for a match with a keyword. My lexer catches all the obvious tokens such as single and multi character operators (+ - * / > < = == etc) (also comments and whitespace are already taken out) so I call a function after I've collec... | If your set of keywords is fixed, a perfect hash can be built for O(1) lookup. Check out gperf or cmph.
|
3,757,492 | 3,757,995 | How to get Click Event of Treeview(CTreeCtrl) in MFC created at runtime? | I have created a treeview at runtime in MFC application , I have added few nodes to it now i want to do some stuff on click of nodes so how i can get click event of treeview ?
My code looks like this :
CTreeCtrl *m_ctlTreeview;
m_ctlTreeview = new CTreeCtrl ;
m_ctlTreeview->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS... | One option is to add a handler for the notification messages for that child window ID (0x1221 in your example) to the parent class at design time using ON_NOTIFY in the message map as usual. If there are no messages, the handler won't be triggered.
Alternatively, you could add a generic WM_NOTIFY handler to the message... |
3,757,752 | 3,757,797 | C++ function call question | i have a question about the function call in the following example:
int main()
{
int a, b;
cin >> a >> b >> endl;
cout << *f(a,b);
return 0;
}
So is *f(a,b) a valid function call?
Edit:: sorry for the errors, i fixed them now i'm a little tired
| The code at least could be reasonable. For it to work, f must be defined as a function that returns either of two sorts of things: either it returns a pointer, in which case the * dereferences the pointer, so whatever it was pointing at gets sent to standard output. Otherwise, f must return some user-defined type that ... |
3,757,800 | 3,758,290 | Return the result of sum of character arrays | Recently in an interview i was asked a question to write a function which takes two character arrays(integers) as input and returns the output character array.
Function Signature:
char* find_sum(char* a, char* b)
How would one approach this?
Example scenario:
find_sum("12345","32142") = "44487"
Note:
The number of di... | u can add huge numbers using the char array approach. however you need to delete the char* after using it every time or use some smart pointer.
char* find_sum(char* a, char* b) {
int lenA = strlen(a), lenB = strlen(b);
int max = lenA > lenB ? lenA : lenB; // Get the max for allocation
char* res = (char*)ma... |
3,757,899 | 3,757,917 | Sorting strings using qSort | According to this site, I have done the following program which sorts strings.
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char list[5][4]={"dat","mai","lik","mar","ana"};
int main(int argc, char *argv[])
{
int x;
puts("sortirebamde:");
for (x=0;x>sizeof(list)/sizeof(char)... | Please note: It is unusual to store C strings in two dimensional char arrays. It's more normal to have char *ary[], such as argv. That type cannot be sorted directly using qsort and strcmp, because qsort will pass char ** not char * to the comparison function. This is good for efficiency, the pointers can be swapped... |
3,758,077 | 3,759,806 | System Time change detection on linux | I was reading about the licensing of software and one question that came to my mind is that "how software detect the change in system time and block themselves if someone changes system time?". Since there is no other reference available(provided we don't have internet connection, otherwise we can use time servers as r... | You could always set the timestamp on a file to the current system time every time your application starts.
Check the time first before setting it - if it's in the future, then the clock has gone backwards since you last set it.
|
3,758,219 | 3,759,512 | How do we register Shell extension with a certain file extension | I have tested a small shell extension referring to the article on code project. Though the whole process is quite complicated , I have some how idea what are the follwoing methodsand what do thet do.:
Initialize,DragQueryFile,GetCommandString,InvokeCommand,QueryContextMenu
But after reading through it I can not under... | One possibility is to register your context menu for all the file extensions you want to support. The other possibility is to register your extension in the wildcard / * class. It will then be instanciated for all files. You can then decide whether the context menu should be visible for this file or not. This can be do... |
3,758,244 | 3,758,425 | Secret to achieve good OO Design | I am a c++ programmer, and I am looking forward to learning and mastering OO design.I have done a lot of search and as we all know there is loads of material, books, tutorials etc on how to achieve a good OO design. Of course, I do understand a good design is something can only come up with loads of experience, individ... |
(very) Simple, but not simplist design (simple enough design if you prefer) : K.I.S.S.
Prefer flat hierarchies, avoid deep hierarchies.
Separation of concerns is essential.
Consider other "paradigms" than OO when it don't seem simple or elegant enough.
More generally : D.R.Y. and Y.A.G.N.I help you achieve 1.
|
3,758,626 | 3,758,896 | Good way to store a wide variety of structures which sizes also vary? | The title is a bit confusing, so i will explain a bit more using examples. Just a note: i am parsing a file format. Say we have a structure like this:
struct example
{
typeA a;
typeB b;
typeX x;
typeY y;
typeZ z;
};
So far its ok. Now the problem is, that typeX, typeY and typeZ can vary in size. Dependi... | The issue for me isn't so much dealing with allocating some space, in concept we can do this:
byte *pA = new byte[the size this time];
but rather what you do with these typeA objects. What does
pA->getValue()
return? Is the intent that it's always, say, a 32 bit numeric? Or do we really have
pA->get16bitValue()
in s... |
3,758,656 | 3,758,695 | C++ template inheritance issue with base types | I have the following code and it fails to compile
template < typename T >
class Base
{
public:
typedef T * TPtr;
void func()
{
}
};
template < typename T >
class Derived : public Base< T >
{
public:
using Base< T >::TPtr;
using Base< T >::func;
TPtr ptr;
};
int main( int c, char *v[] )
... | Base< T >::TPtr is a so-called dependent name so you need to prefix it with typename to make the declaration work.
Additionally, using doesn’t work with typename so you need to use a typedef instead:
typedef typename Base<T>::TPtr TPtr;
The issue is that the compiler can’t decide – without knowing what T is! – whether... |
3,758,698 | 3,758,737 | Is multiple function overloading not permitted with virtual functions? | My program compiles fine, but gets core dumped when an overloaded function is called. Below, is the output of the program:
FoodID supplied=1
FoodBase constructor called
In K constructor
In Omlette constructor
Omlette handler constructor called
In prepare() Omlette Handler
Mix called
K Prepare called
K Egg called
DonePr... | In the Food constructor you create an OmeletteHandler on the stack, this gets destroyed once the function exits.
Food(int foodID)//getting foodID from commandline just for testing purpose
{
OmletteHandler imm;
base=&imm;
}//
You could do base = new OmeletteHandler() instead, (don't forget to delete the poi... |
3,758,956 | 3,759,037 | Reading file input as opcode in C++ | I am working on a project for a class at school. It is a simple implementation of stacks and queues. However as part of the project we are require to read opcode in from a file. The opcode is formated as follows:
append 10
serve
append 20
append 30
serve
push 10
push 50
push 20
push 20
pop
My problem is when I read in... | getline used in that way considers just ' ' as a delimiter, so it won't stop at newlines; moreover, you're not extracting the argument (when the opcodes has any), so it will get read as an opcode (sticked in front of the real opcode) at the next iteration.
In my opinion, you could simply get away with using just the no... |
3,759,079 | 3,759,185 | How can I read the bandwidth in use over the PCIe bus? | I'm working on a streaming media application that pushes a lot of data to the graphics card at startup. The CPU is doing very little at the point when the data is being pushed, it idles along at close to zero percent usage.
I'd like to monitor which machines struggle at pushing the initial data, and which ones can cop... | Do you get errors pushing your massive amounts of data, or are you "simply" concerned with slow speed?
I doubt there's any easy way to monitor PCI-e bandwidth usage, if it's possible at all. But it should be possible to query the bus type the video adapter is connected to via WMI and/or SetupAPI - I have no personal ex... |
3,759,112 | 3,759,152 | What's faster: inserting into a priority queue, or sorting retrospectively? | What's faster: inserting into a priority queue, or sorting retrospectively?
I am generating some items that I need to be sorted at the end. I was wondering, what is faster in terms of complexity: inserting them directly in a priority_queue or a similar data structure, or using a sort algorithm at end?
| Inserting n items into a priority queue will have asymptotic complexity O(n log n) so in terms of complexity, it’s not more efficient than using sort once, at the end.
Whether it’s more efficient in practice really depends. You need to test. In fact, in practice, even continued insertion into a linear array (as in inse... |
3,759,119 | 3,759,177 | Creating an object on the stack then passing by reference to another method in C++ | I am coming from a C# background to C++. Say I have a method that creates a object in a method on the stack, then I pass it to another classes method which adds it to a memeber vector.
void DoStuff()
{
SimpleObj so = SimpleObj("Data", 4);
memobj.Add(so);
}
//In memobj
void Add(SimpleObj& so)
{
memVec.push... |
Yes.
The pointer remains "alive", but points to a no-longer-existent object. This means that the first time you try to dereference such pointer you'll go in undefined behavior (likely your program will crash, or, worse, will continue to run giving "strange" results).
You simply don't do that if you want to keep them a... |
3,759,208 | 3,759,556 | OOP Constructor question C++ | Let's say that I have two classes A and B.
class A
{
private:
int value;
public:
A(int v)
{
value = v;
}
};
class B
{
private:
A value;
public:
B()
{
// Here's my problem
}
}
I guess it's something basic but I don... | Or can I declare an instance of a class and then call a constructor later?
Yes, you can do that. Instead of (A value;) declare (A* value;), and then B's constructor will be B():value(new A(5)){}.
In the B's destructor you will have to do delete value;
I think this could be solved using pointers but can that be avoide... |
3,759,270 | 3,759,297 | Will the destructor of the base class called if an object throws an exception in the constructor? | Will the destructor of the base class be called if an object throws an exception in the constructor?
| If an exception is thrown during construction, all previously constructed sub-objects will be properly destroyed. The following program proves that the base is definitely destroyed:
struct Base
{
~Base()
{
std::cout << "destroying base\n";
}
};
struct Derived : Base
{
Derived()
{
st... |
3,759,410 | 3,759,535 | uuid_generate_random (libuuid) on solaris | I have a simple C++ function that calls "uuid_generate_random". It seems the generated UUID is not standard compliant (UUID Version 4). Any Ideas?
The code I am using is (uuid_generate_random & uuid_unparse functions are available in libuuid):
char uuidBuff[36];
uuid_t uuidGenerated;
uuid_generate_random(uuidGenerated)... | You're quite correct that libuuid seems not to be adhering to the ITU recommendation... It could be argued that the recommendation itself is overly pedantic about retaining version information, as it serves little purpose beyond allowing technorati to easily distinguish how the UUID was generated, but that's beside the... |
3,759,461 | 3,759,515 | Problem with operator < | I have a problem with the operator < that i wrote:
in Node.h :
.
..
bool operator<(const Node<T>& other) const;
const T& GetData ();
.
..
template <class T>
const T& Node<T>::GetData () {
return m_data;
}
template <class T>
bool Node<T>:: operator<(const Node<T>& other) const
{
return (*(this->GetData()) < *(other.G... | Because you used Vehicle*, not Vehicle.
|
3,759,588 | 3,759,665 | QTableView - samples | How to use QTableView in Nokia Qt SDK (for mobiles). I referred some of documents but still I am not clearing about the QTableView. Please any one suggest how to use the QTableView.
I want to show the QTableView with three columns.
| For the table data, you need to implement a model which will hold the data. If you don't require anything special, you can just subclass QAbstractTableModel.
Quoting the most important parts from the documentation:
When subclassing QAbstractTableModel,
you must implement rowCount(),
columnCount(), and data().
Edit... |
3,759,644 | 3,759,739 | C++: Printing/assigning simple array prints gibberish | My code basically is to list ASCII codepoints of a string that is input, my following code is simple, here:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char str[20];
int result[20];
cin >> str;
for(int i = 0; i != strlen(str); i++) {
result[i] = (int)i;
}
... | This loop will iterate a number of times equal to the length of 'str'. That is, it will iterate once for each character in 'str', and stop at the 'null terminator' (char value of 0) which is how c strings are ended. In each loop, the value of 'i' is the loop number, starting at 0 - and this is the value you assign to t... |
3,760,015 | 3,760,038 | can I override the version block in a dll? | Suppose I have built a lot of dlls from a certain revision of the svn repository. (It might by any revisioning system)
I am able to create a resource file containing an entry that denotes the revision number.
Can I link that resource file into the dll's I have already built? Some sort of editbin or the like?
| You can write a small program to do this, using the UpdateResource function in Windows NT:
http://msdn.microsoft.com/en-us/library/ms648049(v=VS.85).aspx
|
3,760,089 | 3,760,287 | How to call a member function on a parameter with std::for_each and boost::bind? | I want to add a series of strings to a combo box using std::for_each. The objects are of type Category and I need to call GetName on them. How can I achieve this with boost::bind?
const std::vector<Category> &categories = /**/;
std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comb... | std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comboBox, boost::bind(&Category::GetName, _1)));
|
3,760,311 | 3,760,328 | Please suggest a good encryption library for VC++ 2008 | I am working on a small project and need your help. Here are the details:
My project is in VC++ 2008
I need to store some critical resource files bundles with my project exe in encrypted form
While running the exe, I want to decrypt and use these files on the fly (without storing decrypted files in temp location)
The ... | Will decrypt key be hardcoded in your program, or supplied from eg. a license file?
If hardcoded, don't bother looking for any type of fancy encryption, all you can hope for is a (very thin!) layer of obfuscation - even a simple XOR scrambling would be no worse than AES.
That said, check out TomCrypt or Crypto++.
EDIT
... |
3,760,332 | 3,760,383 | compilation process in C++ | I will be very grateful, if somebody can actually explain what exactly my compiler does when I press button BUILD, and compiler begins to compile all my .h and .cpp files how exactly this process is going on(what do I have inside object file?), why do I ask such question? I'm trying to understand what does it mean "min... | When doing a full compile, the compiler will read each .cpp file in turn. For a given .cpp file it will then read every file referenced by a #include directive, recursively, compiling the code as it goes. When it compiles the next source file it will read the files referenced with #include in that source file.
When you... |
3,760,731 | 3,760,814 | Exceptions with Unicode what() | Or, "how do Russians throw exceptions?"
The definition of std::exception is:
namespace std {
class exception {
public:
exception() throw();
exception(const exception&) throw();
exception& operator=(const exception&) throw();
virtual ~exception() throw();
virtual const char* what() const throw();... | char* does not mean ASCII. You could use an 8 bit Unicode encoding like UTF-8. char could also be 16 bit or more, you could then use UTF-16.
|
3,761,009 | 3,761,148 | C++: pure virtual assignment operator | why if we have pure virtual assignment operator in a base class, then we implement that operator on the derived class, it give linker error on the base class?
currently I only have the following explanation on http://support.microsoft.com/kb/130486 , it said that the behavior is by design since normal inheritance rules... | From section 12.8 of the standard:
13 The implicitly-defined copy assignment operator for class X performs memberwise assignment of its subobjects. The
direct base classes of X are assigned first, in the order of their declaration in the base-specifier-list, and then the immediate
non-static data members of X are assi... |
3,761,174 | 3,761,225 | Is there a way to statically-initialize a dynamically-allocated array in C++? | In C++, I can statically initialize an array, e.g.:
int a[] = { 1, 2, 3 };
Is there an easy way to initialize a dynamically-allocated array to a set of immediate values?
int *p = new int[3];
p = { 1, 2, 3 }; // syntax error
...or do I absolutely have to copy these values manually?
| You can in C++0x:
int* p = new int[3] { 1, 2, 3 };
...
delete[] p;
But I like vectors better:
std::vector<int> v { 1, 2, 3 };
If you don't have a C++0x compiler, boost can help you:
#include <boost/assign/list_of.hpp>
using boost::assign::list_of;
vector<int> v = list_of(1)(2)(3);
|
3,761,325 | 3,761,342 | Problems in initializing member of a template class | My code does not compile. Below is my code
template <typename T>
class TemplateClass
{
const T constMember;
public:
TemplateClass()
{
constMember = T();
}
};
int main()
{
TemplateClass <int> obj;
}
I get this error :
error: uninitialized member 'TemplateClass<int>::constMember' with... | You are not initializing the const member, you are just assigning to it.
Initialization of members can only be done using a member initialization list.
For example:
TemplateClass() : constMember(T()) //initializes constMember to 0
{}
|
3,761,537 | 3,761,773 | How do I create a rotating cube effect in Qt? | I have a QGraphicsView and a slide show of QGraphicsScenes, at the moment when the user switches to the next slide I just change the Scene that the View is looking at and it changes instantly to reflect that.
What I would like to do it create some transition effects, such as the rotating cube or the slide in/out.
Howev... | Instead of changing the scene that the view sees, you could use property animations to slide graphic items in and out of the view from a single scene. That would give you the slide in/out transition without too much effort. The rotating cube effect would be trickier but I think a reasonable facsimile could be produced ... |
3,761,587 | 3,761,598 | C++ virtual inheritace and typecasting/copy constructor confusion | I have the code below:
class A
{
};
class B: public virtual A
{
public:
B()
{
cerr << "B()";
}
B(const A& a)
{
cerr << "B(const A&)";
}
};
class C: public B
{
};
int main(int argc, char **argv)
{
B *b = new B(C());
}
To my surprise B(const A& a) isn't called. Why is that... | B also has an implicitly declared copy constructor that is declared as
B(const B&);
This implicitly declared member function is called because it is a better match for the argument of type C than your user-declared constructor, B(const A&).
|
3,761,861 | 3,762,020 | Wrap std::vector of std::vectors, C++ SWIG Python | I want to wrap a C++ vector of vectors to Python code by using SWIG.
Is it possible to wrap this type of vector of vectors?
std::vector<std::vector<MyClass*>>;
In the interface file MyApplication.i I added these lines:
%include "std_vector.i"
%{
#include <vector>
%}
namespace std {
%template(VectorOfStructVecto... | Is it a C++ parsing issue?
std::vector<std::vector<MyClass*> >;
---Important space---------------^
|
3,761,914 | 3,761,969 | Storing and retrieving multiple keys in C++ | I have a few integer keys that is needed to retrieve a value. What is the most efficient way to store and retrieve the value based on the keys?
Currently I am converting and combining the three keys into a single string and store the key-value pair in a map. However, I think there should be a more efficient way of doi... | You can almost certainly do better than converting to a string (which is generally quite a slow operation). If your three items have small enough ranges, you can do some shifting and adding to put them together into a single integer with a larger range.
Lacking that, you can just create a struct that holds three ints, ... |
3,762,008 | 3,762,477 | Does map::iterator yield lvalues? | In other words, when i is a map<K,V>::iterator, do the following provide the expected semantics (ie. it modifies the map):
*i = make_pair(k, v);
i->first = k;
i->second = v;
?
Update: The first two lines are invalid, since the return value of operator* is (convertible to?) a pair<const K, V>. What about the third line... | I tried to track this down through the standard:
For a map<Key,T> the value_type is pair<const Key,T> per 23.3.1/2
The map class supports bidirectional iterators, per 23.3.1/1
bidirectional iterator satisfies the requirements for forward iterators, per 24.1.4/1
For a forward iterator a with value_type T, expression *a... |
3,762,033 | 3,762,569 | Unresolved external symbol: @12 vs @8 at the end of symbol name | I don't have any significant experience with C++ but recently had to be involved into the project with C++ part (apache modules, actually).
Right now I am just trying to build some existing very much legacy code and face the very weird problem when VC++ linker cannot find one particular function in the apache library (... | The time_t typedef comes in two flavors, legacy 32-bits that will create the Y2K38 problem and 64-bits, the solution to that problem. You've got a mismatch here.
Check the time.h header file of the CRT you use, there should be a #ifdef in it that selects between the legacy and the 64-bit version. Avoid using legacy i... |
3,762,036 | 3,811,430 | Non-virtual derivation: what do I really get from the compiler? | I am wondering what is produced by the compiler when using non-virtual derivation:
template< unsigned int D >
class Point
{
int[D];
// No virtual function
// ...
};
class Point2 : public Point<2> {};
class Point3 : public Point<3> {};
Does the derivation here only imply compile-time checks? Or is there so... | Ok, looks like no one have so far given you an actual answer to your question:
No, there is no overhead to non-virtual derivation.
The compiler doesn't have to create a vtable, there are no virtual function calls, and all is well.
It is typically implemented simply by placing an instance of the base class at the beginn... |
3,762,309 | 3,762,425 | how to sort a set using a Functor | hey, i am trying to sort my set container using afunctor:
struct CompareCatId : public std::binary_function<Vehicale*, Vehicale*, bool>
{
bool operator()(Vehicle* x, Vehicle* y) const
{
if(x->GetVehicleType() > y->GetVehicleType())
return true;
else if (x->GetVehicleType() == y->G... | A std::set is sorted automatically as you insert elements into it. You don't need to (and you can't) sort it manually.
Just skip sort(begin, end); and everything will be just fine!
Also, in this case your functor mimics operator<, so all you have to write is:
struct CompareCatId : public std::binary_function<Vehicale*,... |
3,762,357 | 3,762,382 | Redirect stdout to Visual Studio output window from native c++ dll | I have a c# windows app that calls a managed c++ dll, which, in turn, calls a native c++ dll. There seem to be some performance issues in the native c++ code, so I'm doing some simple profiling. I'd like to dump the results of the profiling so that the Visual Studio output window picks it up. I thought that printf woul... | Try OutputDebugString
OutputDebugString is rather plain, so I tend to add the following to my projects to make it function like printf (making sure to avoid overrunning the buffer size):
#if (_VERBOSE)
void DebugPrintf (LPTSTR lpFormat, ...)
{
TCHAR szBuf[1024];
va_list marker;
va_start( marker, lpFormat )... |
3,762,371 | 3,762,424 | "Error: no operator for cin>>" I can't figure out what I'm doing wrong here | I'm a student and just started learning C++ last week so this question is probably very low level but I can't figure it out.
I've searched around a bit but can't find any results, or maybe I'm looking for the wrong thing.
There are two cin parts. One taking in an int outside the loop, the other taking in a string insid... | Here is a version that actually compiles. You can figure out what you missed on your own ;-)
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter how many employees you have:";
int numEmployees = 0;
cin >> numEmployees;
for(int i = 0; i < numEmployees; ++i)
{
... |
3,762,429 | 3,762,568 | How to assign keys on physical position at the keyboard on Windows? | There are at least 3 different keyboard layouts who are using the program i make, and i dont care which key they press, the more important thing is where the keys are pressed.
I cant just ask the user to press 100 different keys/combinations, that would take too much time and be very confusing to the user.
Is there so... | This cannot be done. Keyboards do not come with their layout in an electronic form, that could be looked up by the OS. They just send the code for the key pressed, not where the key resides. I'm working on several keyboards daily, which are all classified as having German layout, but with some of the keys being in diff... |
3,762,728 | 3,807,540 | Am I allowed to throw an exception inside MPI-parallelized code? | These are some general questions I am facing while designing the error handling for an algorithm that is supposed to run in parallel using MPI (in C++):
Do Exceptions work inside code that is executed in parallel? Is the behaviour defined?
How do they work? Does that differ for different implementations?
Is it good pr... | Exceptions work the same in an MPI code as with a serial code, but you have to be extremely careful if it is possible for the exception is not raised on all processes in a communicator or you can easily end up with deadlock.
MPI_Barrier(comm); /* Or any synchronous call */
if (!rank) throw Exception("early e... |
3,763,144 | 3,763,181 | Queue Simulation problem | My program is to print the queue of information from a file but i have problem with my following code. When i run the program it keep loop. I cant figure out the problem. Any help?
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <queue>
#include <list>
using namespace std;
void sim... | Your processArrival and processDeparture functions are taking their eventList and printQueue arguments by value. This means that when you call them, for example in this line:
processArrival(newEvent, inFile, eventList, printQueue);
Copies of eventList and printQueue are made and passed into the processArrival function... |
3,763,351 | 3,763,384 | Memory access time slow with VirtualAllocExNuma on Windows 7/64 | In our application we are running on a dual Xeon server with memory configured as 12gb local to each processor and a memory bus connecting the two Xeon's. For performance reasons, we want to control where we allocate a large (>6gb) block of memory. Below is simplified code -
DWORD processorNumber = GetCurrentProcesso... | PAGE_NOCACHE is murder on perf, it disables the CPU cache. Was that intentional?
|
3,763,430 | 3,763,455 | Is there any compiler simulator for mobile phones? | I was wondering if there exists an application for mobile phones(any platform) that simulates compiler, validates syntax?
It would be nice to have one the phone:) Particularly I am looking something for C# or C++(like gcc).
It does not have to generate any output code, just the front-end part(lexilal, syntax analys... | You can try online compilers that work through web browsers, such as Compilr.com.
|
3,763,457 | 3,763,706 | C++ Exception throw annotations on virtual functions | I saw the following snippet code:
class Foo
{
public:
void virtual func() throw (int, float) = 0;
};
class Bar : public Foo
{
public:
void virtual func() throw(short); // line 1: compile error "
// looser throw specifier"
... | Let's break this down. The declaration:
void virtual func() throw (int, float) = 0;
has 2 constructs that you're asking about. the =0 construct tells the compiler that the declared function is 'abstract', which tells the compiler that the function need not be defined in the class Foo (though it can be - but it usual... |
3,763,510 | 3,763,602 | Counting Null Values in an array | Making an uno game for a project.
all 108 cards are located in a filled array named cardDeck[108]
the start function pulls 7 cards at random and fills the players hand by adding
them to an array called playerHand[]
I need help on this please.
1) I don't know how to make the cards dissappear out of the cardDeck array w... | #include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
Make the deck a vector.
vector<Card> deck_;
Insert each card in to the deck.
deck_.push_back(Yellow0);
deck_.push_back(WildDraw4);
Shuffle the deck
srand((unsigned)time(0));
random_shuffle(deck_.begin(), deck_.end());
Take cards out of t... |
3,763,526 | 4,597,225 | How to remove the file which has opened handles? | PROBLEM HISTORY:
Now I use Windows Media Player SDK 9 to play AVI files in my desktop application. It works well on Windows XP but when I try to run it on Windows 7 I caught an error - I can not remove AVI file immediately after playback. The problem is that there are opened file handles exist. On Windows XP I have 2 o... | The problem is that you're not the only one getting handles to your file. Other processes and services are also able to open the file. So deleting it isn't possible until they release their handles. You can rename the file while those handles are open. You can copy the file while those handles are open. Not sure if... |
3,763,621 | 3,768,285 | C++x0 unique_ptr GCC 4.4.4 | I am trying to make use of the unique_ptr from C++x0, by doing
#include <memory>
and comping with -std=c++0x, however it is throwing up many errors this being an example.
/usr/lib/gcc/x86_64-redhat-linux/4.4.4/../../../../include/c++/4.4.4/bits/unique_ptr.h:214: error: deleted function ‘std::unique_ptr<_Tp, _Tp_De... | std::unique_ptr<OtherType> ot("unimportant constructor data");
st->Add(ot);
You cannot pass an lvalue to a function accepting a unique_pointer, because unique_pointer has no copy constructor. You must either move the lvalue (to cast it to an xvalue) or pass a prvalue:
// pass an xvalue:
std::unique_ptr<OtherType> ot("... |
3,763,766 | 3,763,991 | Python or C++? Programming for mobile devices | I am interested in programming for Mobile Devices.
Now I have a phone which runs Symbian S60 3rd, which is one of my motivations for programming for mobile devices.
Now, my question is, which one is better to go for?
Python or C++?
I have a good background in C++ (ANSI), Java and C#.
Thanks.
| There's a large learning curve associated with Symbian C++, if you want to do a quick prototype probably do it in Python.
It depends on what you want your application to do. I believe the Symbian Python implementation was done in some Symbian developers spare time so it may not give you access to everything on the phon... |
3,763,770 | 3,763,810 | What is the difference between same-named inherited function and overridden virtual function? | #include <iostream>
using namespace std;
class base
{
public:
void f() {cout << "base" << endl;}
virtual void v() {cout << "base (virtual)" << endl;}
};
class deriv : public base
{
public:
void f() {cout << "deriv" << endl;}
void v() {cout << "deriv (overridden)" << endl;}
}... | The point is to get polymorphic behavior. If a function in a base-class is declared virtual, and a derived class overrides it, if you call the function using a base class pointer it will automatically call the function in the derived class. If it's not virtual, then it will call the base-class function.
The basic ide... |
3,763,828 | 3,763,847 | A cast that is breaking strict-aliasing rules | I have a function that takes a unsigned long* and needs to pass it to a external library that takes a unsigned int* and on this platform unsigned int/long are the same size.
void UpdateVar(unsigned long* var) {
// this function will change the value at the address of var
ExternalLibAtomicUpdateVar((unsigned int*)... | void UpdateVar(unsigned long* var) {
unsigned int x = static_cast<unsigned int>(*var);
ExternalLibUpdateVar(&x);
*var = static_cast<unsigned long>(x);
}
|
3,763,832 | 4,878,994 | Slow face detection on OpenCV? | I compiled and installed OpenCV (last version from the SVN) on Mac Os X (this is maybe the source of the problem).
The sample works, but the face detection algorithm seems slow to me. The detection time for a face is around 400ms (I just used the example included). The FPS is then quite low.
On youtube and all, I see s... | What is the size of the input image. I am guessing 640x480. Generally people who post YouTube videos resize the image to 160x120. IN full resolution of 640x480 it is very difficult to get more than 2-3 fps. Try to send 160x120 image. You should be getting at least 10fps.
|
3,763,846 | 3,763,887 | What is an in-place constructor in C++? |
Possible Duplicate:
C++'s “placement new”
What is an in-place constructor in C++?
e.g. Datatype *x = new(y) Datatype();
| This is called the placement new operator. It allows you to supply the memory the data will be allocated in without having the new operator allocate it. For example:
Foo * f = new Foo();
The above will allocate memory for you.
void * fm = malloc(sizeof(Foo));
Foo *f = new (fm) Foo();
The above will use the memory a... |
3,763,897 | 3,796,638 | Mixing C++ and Objective-C (Suspected Automake problem) | So, I've been working for some time on connecting hashing out a trivial application, comprising C++ and Objective-C, to prove some concepts and try and learn something.
Here's where I'm at now, my command (being run, and re-run on changes) is
$ autoreconf -vis && make clean && ./configure && make && ./src/greetings
... | From playing around with the zip file, here is what I recommend:
Use a C-only interface on the language boundary. This will avoid automake's non-existent Objective-C++ support. Use the
#ifdef __cplusplus
extern "C"
#endif
trick on your headers to ensure that the C++ compiler is going to generate C functions and the Ob... |
3,763,960 | 3,764,020 | Purpose of C/C++ Prototypes | I was reading wikipedia on C/C++ Prototype statements and I'm confused:
Wikipedia say: "By including the function prototype, you inform the compiler that the function "fac" takes one integer argument and you enable the compiler to catch these kinds of errors."
and uses the below as an example:
#include <stdio.h>
/*
... | Prototypes let you separate interface from implementation.
In your example, all of the code lives in one file, and you could just as easily have moved the fac() definition up where the prototype is currently and removed the prototype.
Real-world programs are composed of multiple .cpp files (aka compilation units), freq... |
3,764,340 | 3,764,392 | Error C2275 caused by template member function. Is this code wrong? | I think I've run into a (possible) VC6 (I know. It's what we use.) compiler error, but am open to the fact that I've just missed something dumb. Given the following code (It's just an example!):
#include <iostream>
// Class with template member function:
class SomeClass
{
public:
SomeClass() {};
template<class T>... | This is likely to be a VC6 issue. Although VC6 compiles most basic templates correctly it is known to have many issues when you start to move towards the more advanced template uses. Member templates are an area where VC6 is known to be weak on conformance.
|
3,764,460 | 3,764,550 | Can VS 2010 check/update header files automatically? | That's pretty much my question: can VS 2010 check and update header files in C++ code automatically? And can VS 2010 automatically generate a cpp file from a header file, saving you the time to copy the function definitions from the header file? I mean, can it figure that there's no implementation for some method and g... | No this feature does not exist in the Visual Studio C++ implementation. Changes to a header file must be manually propagated to the source file and vice versa.
|
3,764,512 | 3,764,553 | How can I get the contents of an std::string into a CFData object? | I've got a function that returns a std::string object. I'm working with Cocoa/CoreGraphics and I need a way to get the data from that string into a CFData object so that I can feed that into a CGDataProviderCreateWithCFData object to make a CGImage.
The CreateCFData function wants a const UInt8* object (UInt8 being a ... | CFDataCreate( NULL, (const UInt8*) myString.data(), myString.size() )
|
3,764,592 | 3,764,661 | Obscure pointer declaration | I have a question which is in some way, I guess, completely trivial: what's that (and why)?
const float *(*const*)(int)
My understanding is that it is a "pointer to a constant pointer to a function taking an int as argument and returning a pointer to constant float".
Is it correct ?
How to "mentally parse" (*const*) ?... | Yes that reasoning is valid. Put it on the right of all '*'es that are not within function parameter lists and on the left of all []'es that are not in function parameter lists. Then you have
const float *(*const* name)(int)
Then read it as usual. From thereon and even how to find the correct place for the name, there... |
3,764,604 | 3,764,642 | Commutative operator overloading + of 2 different objects | I have 2 classes which represent a matrix:
1. RegularMatrix - O(n^2) representation
2. SparseMatrix - a matrix that is represented as linked list (without zeros).
lets say i have:
RegularMatrix a;
SparseMatrix b;
i want to be able to do:
a+b;
and also:
b+a;
so i'm overloading the + operator. My question is, since ... | Yes you need both versions. But you can forward the one to the other, if the operation really is commutative
RegularMatrix operator+(const SparseMatrix &a, const RegualarMatrix &b) {
return b + a;
}
|
3,764,716 | 3,764,884 | C++ visual studio libraries | Is there any way to make static libraries built in Microsoft Visual Studio independent from used CRT (with debug support / without it)?
I mean like, for simple C library it is possible to generate code using gcc and then use the same static library in visual studio. The resulting library.a file is completely independen... | To make a lib that will link in regardless of runtime selection it is necessary to use two switches:
/MT to build against the basic release runtime, /Zl to omit the default library names.
Building against the dll runtimes will cause the compiler to decorate all the runtime symbols with __imp_ (so, for example, it will ... |
3,764,850 | 3,766,483 | Is there anything like VisualAssistX for Eclipse? or I'd like some autocomplete with my cup of Eclipse | I'm currently being forced to work with Eclipse on one of my current projects. The language we're working with is C++.
The one thing I miss the most from Visual Studio is VisualAssistX, mostly for its Auto Complete.
Is there anything like it for Eclipse? Or is there anyway to buff Eclipse's autocompletion?
Thanks a lot... | Eclipse CDT provides auto complete and many more features. The auto-complete in particular is not as robust as VisualAssistX, but it still does a great job.
|
3,764,912 | 3,765,280 | dynamic_cast<> ing variable arguments to templates | I have a C++ application that executes test cases. It is possible that some test cases will depend on output from other test cases.
All test cases implement a basic interface:
/// base class for all test cases
class ITest
{
public:
virtual void Execute() = 0;
};
Test cases that produce some object that may be use... | I see two possible solutions.
static
Make the Register() method a template.
The simple solution would be to limit the number of dependencies to some reasonable maximum.
template <class T, class D1>
void Register(T* test_case, IDependency<D1>* d1)
{
BOOST_STATIC_ASSERT(boost::is_base_and_derived<IDependent<D1>, T>::... |
3,764,916 | 3,765,803 | Using a boost signal within boost::bind | I'm trying to wrap triggering for a boost::signal into a boost::bind object. So what I want is to invoke the signal with some pre-packaged arguments when the boost::function is called.
What I have is this:
boost::signals2::signal<void(int)> sig;
boost::function<void()> f = boost::bind(
&(sig.operator()), &sig, 10);... | An instance of boost::signals2::signal is a function object (a.k.a. functor), and can be bound directly, as described here. The only problem in this case is that a signal is noncopyable, and so it cannot be copied into the object returned by bind. So you first have to wrap it with a boost::ref. Here's an example:
#incl... |
3,764,978 | 3,764,993 | Why hypot() function is so slow? | I did some testing with C++ hypot() and Java Math.hypot. They both seem to be significantly slower than sqrt(a*a + b*b). Is that because of a better precision? What method to calculate a hypotenuse hypot function uses? Surprisingly I couldn't find any indication of poor performance in the documentation.
| It's not a simple sqrt function. You should check this link for the implementation of the algorithm: http://www.koders.com/c/fid7D3C8841ADC384A5F8DE0D081C88331E3909BF3A.aspx
It has while loop to check for convergence
/* Slower but safer algorithm due to Moler and Morrison. Never
produces any intermediate resu... |
3,765,011 | 3,765,799 | C++: Read from files? |
Possible Duplicate:
Reading through file using ifstream
I'm trying to find a way to read something from a file, put it into a string and then output it onto the screen. If you know how to do this can you give an example?
| ifstream infile("myfile.txt");
std::string line;
// Reads the first line from the file and stores it into 'line'
std::getline(infile, line);
infile.close();
std::cout << line;
This code will read the entire first line of the file.
If you want to read the file line by line you could do something like this:
while (!in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.