Address of an instance emplaced to std::vector is invalid - c++11

I have 2 std::vectors:
to first vector, I emplace instance
to second vector, I want to store the address of the instance just emplaced
But it does not work, i.e., the stored address differs from the emplaced instance's address.
If it matters at all, I'm on Linux and using g++ 5.1 and clang 3.6 with -std=c++11.
Here's a working example to illustrate the problem.
#include <iostream>
#include <vector>
struct Foo {
Foo(int a1, int a2) : f1(a1), f2(a2) {}
int f1;
int f2;
};
int main(int, char**) {
std::vector<Foo> vec1;
std::vector<Foo*> vec2;
int num = 10;
for (int i = 0; i < num; ++i) {
vec1.emplace_back(i, i * i);
// I want to store the address of *emplaced* instance...
vec2.push_back(&vec1.back());
}
// same
std::cout << "size 1: " << vec1.size() << std::endl;
std::cout << "size 2: " << vec2.size() << std::endl;
// same for me
std::cout << "back 1: " << &vec1.back() << std::endl;
std::cout << "back 2: " << vec2.back() << std::endl;
// typically differ ?
std::cout << "front 1: " << &vec1.front() << std::endl;
std::cout << "front 2: " << vec2.front() << std::endl;
for (int i = 0; i < num; ++i) {
std::cout << i + 1 << "th" << std::endl;
// same for last several (size % 4) for me
std::cout << "1: " << &vec1[i] << std::endl;
std::cout << "2: " << vec2[i] << std::endl;
}
}
Questions
Is it correct behavior ? I guess it's caused by storing the address of temporary instance but I want to know whether it's permitted by the standard (just curious).
If above is true, how to work around this ? I resolved this by changing first one to vector<unique_ptr<Foo>> but is there any idiomatic way ?

Two options:
1) You can simply fix your test. You just need in you test preallocate enough memory first with
vec1.reserve(10);
Well, this is implementation details for std::vector. As more and more items are added to std::vector it needs to get more space for them. And this space must be contigious. So when there is not enough space for a new element std::vector allocates a bigger block of memory, copies existing elements to it, add the new element and finally frees the block of memory that it used before. As a result addresses that you stored in vec2 might become invalid.
However, if you preallocate enough memory for 10 elements then you code is correct.
Or, since reserving memory is sort of tricky thing to do
2) use std::deque since insertion and deletion at either end of a deque never invalidates pointers or references to the rest of the elements (http://en.cppreference.com/w/cpp/container/deque) and forget about the problem with invalidated addresses. So no need to reserve memory.

Related

Is it possible to place a std::array at a fixed memory address?

For an embedded design I want to place a C++ std::array at a specific memory address, which points to a buffer shared by hardware and software. Is this possible?
Try Placement new:
#include <array>
#include <iostream>
int main()
{
alignas(double) char buffer[100];
auto parr = new (buffer) std::array<double, 3> {3.14, 15.161, 12};
const auto & arr = *parr;
std::cout << (void*) &arr << " " << (void*) buffer << "\n";
for (auto x: arr)
std::cout << x << " ";
std::cout << "\n";
}
which may give this output:
0x7ffcdd906770 0x7ffcdd906770
3.14 15.161 12
One thing to be worried about is whether the address you want to use is consistent with the alignment requirements of the data you want to hold in the array. Most likely you will be dealing with chars, floats or ints, so this condition shouldn't be difficult to enforce.
For embedded code, two simple solutions spring to mind:
Declare extern int myArray[1234] ; and then define myArray (or rather its mangled form) in your linker definition file.
Define a macro: #define myArray ((int*)0xC0DEFACE)
The first solution is for the purists; the second is for the pragmatists.

Which one to choose between pointer way and non pointer way?

#include <iostream>
class A{
public:
A(){std::cout << "basic constructor called \n";};
A(const A& other) {
val = other.x
std::cout << "copy constructor is called \n";
}
A& operator=(const A& other){
val = other.x
std::cout << "\n\nassignment operator " << other.val << "\n\n";
}
~A(){
std::cout << "destructor of value " << val <<" called !!\n";
}
A(int x){
val = x;
std::cout << " A("<<x<<") constructor called \n";
}
int get_val(){
return val;
}
private:
int val;
};
int main(){
// non pointer way
A a;
a = A(1);
std::cout << a.get_val() << std::endl;
a = A(2);
std::cout << a.get_val() << std::endl;
// pointer way
A* ap;
ap = new A(13);
std::cout << ap->get_val() << std::endl;
delete ap;
ap = new A(232);
std::cout << ap->get_val() << std::endl;
delete ap;
return 0;
}
I initially create an object out of default constructor and then assign tmp r-value objects A(x) to a. This ends up calling assignment operator. So in this approach there are 3 steps involved
(non-pointer way)
1) constructor
2) assignment operator
3) destructor
Where as when I use pointer it only requires two step
(pointer way)
1) constructor
2) destructor
My question is should I use non-pointer way to create new classes or should I use pointer way. Because I have been said that I should avoid pointers (I know I could also use shared_ptr here).
Rule of thumb: Prefer to create objects on the stack. There is less work for memory management when you create objects on the stack. It is also more efficient.
When do you have to create objects on the heap?
Here are some situations that need it:
You need to create an array of objects where the size of the array is known only at run time.
You need an object to live beyond the function in which it was constructed.
You need to store and/or pass around a pointer to a base class type but the pointer points to a derived class object. In this case, the derived class object, most likely, will need to be created using heap memory.

C++ MurmurHash3 returning same value for different key

I am confused with how should i call MurmurHash3_x86_128() when i have lot of key value. The murmurhash3 code can be found https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp. Method definition is given below.
void MurmurHash3_x86_128 ( const void * key, const int len,
uint32_t seed, void * out )
I am passing different key value using a for loop as shown below but still the hash value return is same. If i am removing for loop and passing individual key value then the value is different. What am i doing wrong ?
int main()
{
uint64_t seed = 100;
vector <string> ex;
ex.push_back("TAA");
ex.push_back("ATT");
for(int i=0; i < ex.size(); i++)
{
uint64_t hash_otpt[2]= {};
cout<< hash_otpt << "\t" << endl;
const char *key = ex[i].c_str();
cout << key << endl;
MurmurHash3_x64_128(key, strlen(key), seed, hash_otpt); // 0xb6d99cf8
cout << hash_otpt << endl;
}
return 0;
The line
cout << hash_otpt << endl;
is emitting the address of hash_otpt, not its contents.
It should be
cout << hash_otpt[0] << hash_otpt[1] << endl;
Basically the 128-bit hash is split and stored in two 64-bit unsigned integers (the MSBs in one and the LSBs in another). On combining them, you get the complete hash.

performing N independent 1D FFT on a 2D matrix with FFTW

I have a 2 dimensional matrix with each column corresponding to one independent signal. I am going to perform N 1D fft on each column. In matlab, apply a fft to a 2D matrix will do the trick. But I am porting my code to c++ with fftw. I wonder if there is a way to do so. I try the following code by setting the column size to 1 and row size to 4 (total row number), but it does not help.
#include <iostream>
#include <complex>
#include "fftw3.h"
using namespace std;
int main(int argc, char** argv)
{
complex<double> data[4][2];
data[0][0] = complex<double>(1,1);
data[1][0] = complex<double>(2,1);
data[2][0] = complex<double>(3,1);
data[3][0] = complex<double>(4,1);
data[0][1] = complex<double>(1,1);
data[1][1] = complex<double>(1,2);
data[2][1] = complex<double>(1,3);
data[3][1] = complex<double>(1,4);
cout << "original data ..." << endl;
cout << data[0][0] << '\t' << data[0][1] << endl;
cout << data[1][0] << '\t' << data[1][1] << endl;
cout << data[2][0] << '\t' << data[2][1] << endl;
cout << data[3][0] << '\t' << data[3][1] << endl;
cout << endl << endl;
fftw_plan plan=fftw_plan_dft_2d(4, 1,(fftw_complex*)&data[0][0], (fftw_complex*)&data[0][0], FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(plan);
cout << "after fftw ..." << endl;
cout << data[0][0] << '\t' << data[0][1] << endl;
cout << data[1][0] << '\t' << data[1][1] << endl;
cout << data[2][0] << '\t' << data[2][1] << endl;
cout << data[3][0] << '\t' << data[3][1] << endl;
return 0;
}
Above code takes the first and second row and reshape them to 2x2 matrix then perform a 2D fft.
Up to now, the only way that comes to my mind is as follow. Let's say I have NxM (N rows, M columns), I create M fftw plans for M 1D fftw. I execute M fftw in serial to get the result. But in practical application, the matrix is very big, M is so large. It is very inefficient to do this way. Any better idea? Thanks.
For those stumbling across this nowadays, the FFTW devs have implemented routines for this operation, which is faster than looping through each column and taking a separate transform. You certainly don't want to take a 2D transform (as is shown in the question), which is mathematically different than row-wise 1D transforms.
The key to you question is in fftw_plan_many_dft. Here is a link to the full documentation.
Here is an example (modifed from the above link) that illustrates what you're looking for.
#include "fftw3.h"
int main() {
fftw_complex *A; // array of data
A = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*10*3);
// ...
/* Transform each column of a 2d array with 10 rows and 3 columns */
int rank = 1; /* not 2: we are computing 1d transforms */
int n[] = {10}; /* 1d transforms of length 10 */
int howmany = 3;
int idist = 1;
int odist = 1;
/* distance between two elements in the same column */
int istride = 3;
int ostride = 3;
int *inembed = n, *onembed = n;
/* forward, in-place, 1D transform of each column */
fftw_plan p;
p = fftw_plan_many_dft(rank, n, howmany, A, inembed, istride, idist, A, onembed, ostride, odist, FFTW_FORWARD, FFTW_ESTIMATE);
// ...
/* run transform */
fftw_execute_dft(p, A, A);
// ...
/* we don't want memory leaks */
fftw_destroy_plan(p);
fftw_free(A);
}

c++11 Why doesn't this move constructor work?

I've written the code posted below. I was hoping to get to move the content of a vector between instances of LargeClass. The move constructor is being used, but instead of moving I get copies only.
Why doesn't the move semantics work as expected here?
Code:
#include <iostream>
#include <vector>
class LargeClass
{
public:
explicit LargeClass (void): numbers(20, 10)
{
}
LargeClass (const LargeClass &rhs): numbers(rhs.numbers)
{
std::cout << "Using LargeClass copy constructor" << '\n';
}
LargeClass (const LargeClass &&rhs): numbers(std::move(rhs.numbers))
{
std::cout << "Using LargeClass move constructor" << '\n';
}
const int* getNumbersAddress(void) const
{
return (numbers.data());
}
private:
std::vector<int> numbers;
};
int main()
{
LargeClass l1;
std::cout << "l1 vector address: " << l1.getNumbersAddress() << '\n';
LargeClass l2(l1);
std::cout << "l1 vector address: " << l1.getNumbersAddress() << '\n';
std::cout << "l2 vector address: " << l2.getNumbersAddress() << '\n';
LargeClass l3 = std::move(l2);
std::cout << "l1 vector address: " << l1.getNumbersAddress() << '\n';
std::cout << "l2 vector address: " << l2.getNumbersAddress() << '\n';
std::cout << "l3 vector address: " << l3.getNumbersAddress() << '\n';
return 0;
}
Possible output:
l1 vector address: 0x18ce010
Using LargeClass copy constructor
l1 vector address: 0x18ce010
l2 vector address: 0x18ce070
Using LargeClass move constructor
l1 vector address: 0x18ce010
l2 vector address: 0x18ce070
l3 vector address: 0x18ce0d0
The rvalue references don't make sense in their const forms because you want to modify them (you want to "move" them ). Objects created as const in C++ are in read-only memory, from which grabbing/modifying internal resources won't be possible.
The syntax for move constructor normally should be
class_name ( class_name && )
So use :
LargeClass ( LargeClass&& rhs )
Although a constructor taking const LargeClass&& is technically known as a move constructor (12.8/3) (which is baffling, but explicitly stated in [C++11: 12.8/3]), it's pretty bloomin' useless; it's self-evident that you cannot move from a const expression, because you cannot modify const things and moving implies altering the source! In particular, you cannot actually move from a const vector, which is why that does not occur here and why you see what you see.
A more useful move constructor looks like this:
LargeClass(LargeClass&& rhs)

Resources