logo
down
shadow

Ensure a `std::vector` won't move its pointer


Ensure a `std::vector` won't move its pointer

By : Reza Farsi
Date : November 22 2020, 03:01 PM
this one helps. No, std::vector doesn't provide a direct way of doing that.
std::vector allocates space via an allocator object though. If you wanted to, it would be fairly easy to write a minimal allocator that had an extra call to disable allocation and call abort if allocation were attempted after it was disabled.
code :


Share : facebook icon twitter icon
c++ vector of shared pointer. If casted outside of vector, will it change the pointer in vector?

c++ vector of shared pointer. If casted outside of vector, will it change the pointer in vector?


By : ajcrwl
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I've just noticed the code you added to the question. SharedPointers doesn't do that.
SharedPointers are "shared" in terms of 'reference counting', not "shared" in terms of "datasharing". "data sharing" in your terms is done by .. pointers. Whatever you want to "share", refer to it by pointer. Then, if you change it, everyone will see the update. But You must change it, not the pointer to it.
code :
// obj_array and container are a vector<shared_ptr<Base>*>
// or a vector<shared_ptr<shared_ptr<Base>>>

obj_array.push_back(new std::shared_ptr<Base>(new Base()); // note the 'new'
container.push_back(obj_array[0]]);

(*obj_array[0]) .reset(Child_A()); // note the '*'

obj_array[0] -> reset(Child_A()); // or, just in short
vector<Base*> vector;
vector.resize( 10 );

///// .... later ....

Base* olditem = vector[ 4 ];
Base* newitem = new Bar();

bool iWillDeleteTheOld = well_somehow_decide();

vector[4] = newitem;
moduleB->updateAfterReplace(olditem, newitem,  iWillDeleteTheOld);
modulec->updateAfterReplace(olditem, newitem,  iWillDeleteTheOld);

if(iWillDeleteTheOld)
   delete olditem;

///// .... later ....

for( ... idx ...)
    delete vector[idx];

vector.resize(0);
vector<shared_ptr<Base>> vector;
vector.resize( 10 );

///// .... later ....

sharedptr<Base> olditem = vector[4];
sharedptr<Base> newitem = new Bar();

vector[4].reset( newitem ); // <- THE LINE

moduleB->updateAfterReplace(olditem, newitem);
modulec->updateAfterReplace(olditem, newitem);

///// .... later ....

vector.resize(0);
vector<Base**> vector;
for(int i = 0; i<10; ++i)
   vector.push( new Base* );

///// .... later ....

Base* olditem = * vector[4]; // note the dereference
Base* newitem = new Bar();

bool iWillDeleteTheOld = well_somehow_decide();

* vector[4] = newitem; // note the dereference

if(iWillDeleteTheOld)
   delete olditem;

///// .... later ....

for( ... idx ...)
{
    delete * vector[idx];  // delete the object
    delete vector[idx]; // delete the pointer
}

vector.resize(0);
vector<sharedptr<sharedptr<Base>>> vector;
for(int i = 0; i<10; ++i)
   vector.push( new sharedptr<Base> );

///// .... later ....

(* vector[4] ).reset( new Bar() ); // note the dereference

///// .... later ....

vector.resize(0);
shared_ptr<Foo> first = new Foo(1);
shared_ptr<Foo> second = first;
shared_ptr<Foo> third = second;

// now first == Foo#1   \
// now second == Foo#1  | refcount = 3
// now third == Foo#1   /

third.reset( new Bar(2) );

// now first == Foo#1   \ refcount = 2
// now second == Foo#1  /
// now third == Bar#2   - refcount = 1

second.reset( new Asdf(3) );

// now first == Foo#1   - refcount = 1
// now second == Asdf#3 - refcount = 1
// now third == Bar#2   - refcount = 1

first.reset( third );

// now first == Bar#2                   \
// now second == Asdf#3 - refcount = 1  | - refcount = 2
// now third == Bar#2                   /
// and Foo#1 gets deleted
Ensure move in std vector with trivial type

Ensure move in std vector with trivial type


By : Sam N
Date : March 29 2020, 07:55 AM
hope this fix your issue Say I have a vector of ints , Make an uncopyable wrapper:
code :
#include <vector>

template<typename T>
class   uncopyable
{
public:
  uncopyable(const uncopyable&) = delete;

  uncopyable(uncopyable&&) = default;

  uncopyable(T&& data)
    :
    data_(std::move(data))
  {
  }

public:
  uncopyable&   operator=(const uncopyable&) = delete;

  uncopyable&   operator=(uncopyable&&) = default;

  uncopyable&   operator=(T&& data)
  {
    data_ = std::move(data);
    return *this;
  }

private:
  T       data_;
};

int     main()
{
  std::vector<int>      big(10000);

  uncopyable<std::vector<int>>  uncopyable_big(std::move(big));

  std::vector<int>      other_big(10000);

  uncopyable_big = std::move(other_big);
}
std::vector, std::move and pointer invalidation

std::vector, std::move and pointer invalidation


By : Alexander Vorovchenk
Date : March 29 2020, 07:55 AM
hop of those help? The pointers will remain valid. According to the behavior of move constructor of std::vector:
How should I ensure the call to the move constructor? (move semantics and rvalue reference)

How should I ensure the call to the move constructor? (move semantics and rvalue reference)


By : Vitamin Ex
Date : March 29 2020, 07:55 AM
seems to work fine to the commenters, I found out that the compiler is doing return value optimization (RVO) which prevents the calls to the constructors written above. I found a way to disable RVO. The -fno-elide-constructors switch in g++ works.
How do I move a unique pointer from one vector to another vector of unique pointers?

How do I move a unique pointer from one vector to another vector of unique pointers?


By : Gaurav sharma
Date : March 29 2020, 07:55 AM
I hope this helps you . Well, in that case you have two conceptually independent operations:
code :
destination.emplace(destination.begin() + m, std::move(source[n])); // or .insert()
source.erase(source.begin() + n);
Related Posts Related Posts :
  • std::is_pointer check with universal references
  • stack error while trying to modify hbitmap data
  • Include external .asm file into C++ code
  • Adapting a fixed-sized chunk pool allocator to certain STL containers
  • C++ passing a mutex to a member variable in the constructor
  • OpenMP conditional critical
  • About letter f (float type) in C/C++
  • Determining if a pack is empty or not
  • What is template<> template<> syntax in the context of template-alias for?
  • Understanding of a specific function Determinant of a Matrix
  • Dynamically add QWebEngineView to layout
  • Linux platform tag for python module built with pybind11
  • Copy and Base Constructor don't initialize C++
  • Xcode gives Mach-O linker error: "_JNI_CreateJavaVM", referenced from: _main in main.o
  • Variadic deduction guide not taken by g++, taken by clang++ - who is correct?
  • Write a proxy class in C++
  • Qt testing when dependent on Network
  • RGB color in 24 bitmap image and 16 bitmap image
  • shadertoy to SFML
  • Inserting Objects into an array with dynamic memory (No vectors allowed) C++
  • Find parent node function for binary tree
  • Rotate Binary Tree
  • Boost asio async_read_until stop reading on matched condition
  • How can I change the QGraphicView selected Item color
  • Understanding object slicing
  • How to change pointer so that it point to somewhere else?
  • Dynamically add overlay widgets
  • Compressing 3 number data in a byte
  • OpenGL - Uniform not being passed properly?
  • C++ Visual Studio "Non-standard syntax; use '&' to create a pointer to member"
  • Doxygen won't resolve reference to typedef in namespace
  • How to test for assert in debug build, but returned value in release?
  • use boost spirit parse int pair to vector
  • How #define works in Programming when define has value with operator?
  • C++: Passing objects by value to a member function of the same class
  • Confusion in C++ constructor
  • Implicit conversion operator doesn't kick in with operator overloading
  • From tuple of N elements to tuple of N/2 pairs
  • Operators Not Working With Class Objects?
  • GDAL Not Linking
  • C++ aligning characters to display neatly with any input implemented
  • c++, method to display content in hash table.Using double linked list
  • How to apply a function to a variadic argument list and cat them to a tuple
  • Doubly linked list c++ crashing after 3rd node
  • Transform a specific type of argument using templates
  • Function with recursion is causing stack overflow
  • working with multi-word typedefs
  • Calling std::to_string or std::to_wstring based on given typedef
  • Appopriate Container that acts like normal static array?
  • Using enable_if to disable a template constructor of a template class
  • define implicit conversion from template class to primitive type based on other template
  • C++ class template, how to overload [ ] operator in a specific stuation?
  • What is the purpose of using an iterator in this function's return value?
  • C++ overriding the value of inherited static const variables
  • C++: what is special about punning character arrays according to the standard?
  • Producer consumer pthreads program not finishing
  • How do I start two thread teams with different thread functions at the same time?
  • OpenGL 3.3: GL_INVALID_OPERATION when calling glBindBuffer
  • Boost Karma generator for composition of classes
  • Can the storage of trivially copyable objects be safely reallocated with realloc?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org